Reputation: 8137
I'm new to object oriented programming in PHP. I included a class and called it, then, inside this class's constructor I'm calling a private function called handleConnections. For some reason, it's giving me a fatal error (undefined function). Any idea why?
The class:
class Test
{
function __construct()
{
handleConnections();
}
private function handleConnections()
{
//do stuff
}
}
It seems flawless and yet I'm getting this error. If anyone has any clue what might be wrong, please tell me. Thanks!
Upvotes: 1
Views: 456
Reputation: 61577
Just expanding on FWH's Answer.
When you create a class and assign it to a variable, from outside the class you would call any function within that class using $variable->function();. But, because you are inside the class, you don't know what the class is being assigned to, so you have to use the $this-> keyword to access any class properties. General rule of thumb, if you would access it like $obj->var, access it with $this->.
class myClass
{
function myFunc()
{
echo "Hi";
}
function myOtherFunc()
{
$this->myFunc();
}
}
$obj = new myClass;
// You access myFunc() like this outside
$obj->myFunc();
// So Access it with $this-> on the inside
$obj->myOtherFunc();
// Both will echo "Hi"
Upvotes: 4
Reputation: 3223
Try with:
$this->handleConnections();
If you don't prefix your calls with $this, it's trying to call a global function. $this is mandatory in PHP, even when there can be no ambiguity.
Upvotes: 4