简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM