views:

100

answers:

2

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!

+4  A: 

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.

FWH
+3  A: 

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"
Chacha102
In proper OO languages like Java, from inside a class you can call its methods and fields without using this
Click Upvote
Just to add on, this apply to variables as well, and it's a source of hidden bugs.
Extrakun