Search code examples
phpooppyrocms

Defining a var in constructor cause "Creating default object from empty value error"


I'm using PyroCMS with PHP 5.4.15 in my development server, so I installed a new module (created by someone else) and get this warning all the time:

A PHP Error was encountered

Severity: Warning

Message: Creating default object from empty value

Filename: admin/newsletters.php

Line Number: 63

This is the line 63:

$this->data->pagination = create_pagination('admin/newsletters/index', $total_rows);

So reading at PHP doc and Google seems to the var $this->data isn't initialized so in the constructor of the clase I declared as follow:

public function __construct() {
        parent::__construct();

        $this->data = "";
}

But the error still appearing, so my question are:

  1. What's wrong in my solution?
  2. If I declare or define a var in the class constructor this var is initialized or not? (this is the related OOP part)

Solution

  • You do not need to initialise like you would in functional PHP. Define it in your class is enough for it to exist in the object, for you to use as you like.

    Class extends Parent {
      public $data;
    
      public function __construct() {
        parent::__construct();
        $this->data = 'Hello, world!';
      }
    }
    

    Used as...

    $new = new Class();
    echo $new->data;
    // Hello, world!
    

    and similarly...

    $new = new Class();
    $new->data = 'Goodbye, cruel world.';
    echo $new->data;
    // Goodbye, cruel world.