Fatal error: undefined function - why?

萝らか妹 提交于 2020-01-03 02:49:29

问题


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!


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/1150108/fatal-error-undefined-function-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!