简体   繁体   中英

Fatal error: Call to a member function display() on a non-object

this is my code for creating a list of data elements ! in this below line mentioned there are two error(on the same line)

1)Notice: Undefined offset: 0 2)Fatal error: Call to a member function display() on a non-object

  <?php
  class data
  {
     public $num;
     public $Char;


    function __construct()
    {
      $this->num= "null";
      $this->Char= "New Char";    
    }

    public function setInt($int)
    {
      $this->num=$int;
    }

    public function setChar($char)
    {
      $this->Char= $char;
    }


    public function getInt()
    {
      return $this->num;
    }

    public function getChar()
    {
     return $this->Char;
    }

    public function display()
    {
      echo $this->num;
      echo $this->Char;
    }
  }

  class linklist extends data 
  {
    public $DATA;
    private $list;
    private $count;

    function __construct()
    {
      $DATA= new data();
      $list= array();
      $count=0;
    }

    function addData(data $d)
    {
       $this->list[$this->count]= $d;

     $this-> count++;
    }   

    function displayy()
    {
        $d= new data();
        $i=0;
      for($i;$i<=$this->count; $i++)
      {
        $this->list[$i]->display();   //** line with error *** //
      }

    }
  }




?>




<!DOCTYPE html>
<html>
<body>
<?php
   $d= new data();

     //$d->display();

     //$Name= $_POST['fname'];
     //$Age = $_POST['age']; 


     $d->setInt("1");    
     $d->setChar("Ashad");   

     //$d->display();

     $d1= new Data();

     $d1->setInt("2");   
     $d1->setChar("shahrukh");   

     $list = new linklist();

     $list-> addData($d);
     $list->addData($d1);


    $list->displayy();


?>  
</body>
</html>

The constructor of linklist should be:

function __construct()
{
  $this->DATA= new data();
  $this->list= array();
  $this->count=0;
}

You have been missing the $this

Also note the comment of @NB :

for($i; $i <= $this->count; $i++)

should be

for($i = 0; $i < $this->count; $i++)

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