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

一世执手 提交于 2019-12-20 03:14:23

问题


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!


回答1:


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).



来源:https://stackoverflow.com/questions/3760743/php-fatal-error-call-to-undefined-method-why

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