PHP,致命错误:调用未定义的方法,为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3760743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:00:13  来源:igfitidea点击:

PHP, Fatal error: Call to undefined method, why?

phpoopclassmethodsundefined

提问by yossi

I have a simple php structures.

我有一个简单的 php 结构。

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!

谢谢!

回答by Artefacto

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 validateDatayou invoke a method on a null variable.

在第一种情况下,您设置的是局部变量,而不是字段,因此它仍然是null. 然后在validateData你调用一个空变量上的方法。

I'm assuming you snipped some code, because your Ingredientclass doesn't make sense (there's a $validatevariable there that isn't defined).

我假设您剪断了一些代码,因为您的Ingredient类没有意义(那里有一个$validate未定义的变量)。