1

我是 PHP 中面向对象编程的新手。我包含了一个类并调用了它,然后,在这个类的构造函数中,我调用了一个名为 handleConnections 的私有函数。出于某种原因,它给了我一个致命错误(未定义的函数)。知道为什么吗?

班上:

class Test
{
   function __construct()
   {
      handleConnections();
   }

   private function handleConnections()
   {
      //do stuff
   }
}

它看起来完美无瑕,但我收到了这个错误。如果有人知道可能出了什么问题,请告诉我。谢谢!

4

2 回答 2

4

尝试:

$this->handleConnections();

如果您没有在调用前加上 $this,它会尝试调用全局函数。$this 在 PHP 中是强制性的,即使没有歧义。

于 2009-07-19T15:22:26.207 回答
4

只是扩展了 FWH 的答案。

当您创建一个类并将其分配给一个变量时,您可以使用 $variable->function(); 从类外部调用该类中的任何函数。但是,因为您在类中,所以您不知道该类被分配给什么,因此您必须使用 $this-> 关键字来访问任何类属性。一般的经验法则,如果您想像 $obj->var 一样访问它,请使用 $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"
于 2009-07-19T15:29:36.910 回答