致命错误:未定义函数 - 为什么? [英] Fatal error: undefined function - why?
问题描述
我是PHP中面向对象编程的新手。我包含一个类并调用它,然后,在这个类的构造函数中,我调用一个名为handleConnections的私有函数。出于某种原因,它给了我一个致命的错误(未定义函数)。任何想法为什么?
类:
class Test
{
函数__construct()
{
handleConnections();
private function handleConnections()
{
// do stuff
}
}
看起来完美无瑕,但我得到这个错误。如果任何人有任何线索可能是错误的,请告诉我。谢谢!
只要扩展FWH的答案即可。 创建一个类并将其分配给一个变量,从类外部使用$ variable-> function();来调用该类中的任何函数。但是,因为你在类内部,所以你不知道该类被分配了什么,所以你必须使用$ this->关键字来访问任何类的属性。一般的经验法则,如果你想像$ obj-> var那样访问它,可以用$ this - >来访问。
pre code> class myClass
{
函数myFunc()
{
echoHi;
函数myOtherFunc()
{
$ this-> myFunc();
}
}
$ obj = new myClass;
//你可以在
$ obj-> myFunc()之外访问myFunc();
//所以使用$ this->访问它。在内部
$ obj-> myOtherFunc();
//两者都会回显Hi
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!
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"
这篇关于致命错误:未定义函数 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!