PHP,致命错误:调用未定义的方法,为什么? [英] PHP, Fatal error: Call to undefined method, why?
本文介绍了PHP,致命错误:调用未定义的方法,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的php结构。
class成分和类成分,我有这个代码:
class Ingredient
{
public function objectIsValid()
{
return $ validate [0];
}
}
类成分
{
public $ ingObject;
function __construct(){$ ingObject = new Ingredient(); }
public function validateData()
{
if($ this-> ingObject-> objectIsValid()/ ***错误*** /)
{echoOK;}
else
{echoNOT;}
}
}
$ Ingridients =新成分();
$ Ingridients-> validateData();
我只是不明白为什么我得到错误..
$ b $解决方案 / div>
function __construct(){$ ingObject = new Ingredient(); }
应为
function __construct(){$ this-> ingObject = new Ingredient(); }
在第一种情况下,您设置的是局部变量而不是字段, code> null 。然后在 validateData
上调用一个空变量的方法。
我假设你剪断了一些代码,因为你的成分
类没有意义(有一个 $ validate
变量没有定义)。
I have a simple php structures.
class Ingredient and class Ingredients, i have this code:
class Ingredient
{
public function objectIsValid()
{
return $validate[0];
}
}
class Ingredients
{
public $ingObject;
function __construct(){ $ingObject = new Ingredient(); }
public function validateData()
{
if($this->ingObject->objectIsValid() /*** THE ERROR ***/)
{ echo "OK";}
else
{ echo "NOT";}
}
}
$Ingridients = new Ingredients();
$Ingridients->validateData();
I just can't understand why do i get the error..
any help will be appreciated.
thanks!
解决方案
function __construct(){ $ingObject = new Ingredient(); }
ought to be
function __construct(){ $this->ingObject = new Ingredient(); }
In the first case you're setting a local variable, not a field, so it remains null
. Then on the validateData
you invoke a method on a null variable.
I'm assuming you snipped some code, because your Ingredient
class doesn't make sense (there's a $validate
variable there that isn't defined).
这篇关于PHP,致命错误:调用未定义的方法,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文