I’m trying to refactor some code but I’m kinda confused. I define my database connection like so:
try{
global $conn;
$conn = new PDO("mysql:host=$host",$root,$pw); [...]
Now I’d like a function for retrieving table rows but it needs $conn. Is there any way in which I can pass $conn into this function? I tried to set it as a default value but that doesn’t work:
function get($table,$conn=$conn,$limit=10){ [...]
I then tried the use keyword but I think it’s only available for anonymous functions:
function get($table,$limit=10)use($conn){
$query = $conn->query(" [...]
How do other people do this? Am I missing something obvious here?
As you already wrote in your question, this function header is incomplete. The function itself can not do what it needs to do without having
$conn.As this is a function in the global namespace, the most straight forward thing could be to use a global variable:
I also name-spaced the function to make the relation clear. The problem with this are two things:
So what you normally do in that case is to wrap this into a class:
You then pass around a
Connobject which can be used:And then:
The private variable takes over the role of the global variable with the benefit that every method inside the same object can access it. So everything now is in it’s own space and contrary to the global space, will not go into each others way that fast. This is easy (easier) to change and maintain over time.