Ha Dev
Ha Dev

Reputation: 93

Cake PHP 0.2.9 - Constructor issue

I am working on the old Cakephp version 0.2.9

I tried to write a constructor

function __construct and function __construct() and with the same class name

But all getting error like Fatal error: Call to a member function init() on a non-object in ..

Upvotes: 0

Views: 590

Answers (1)

AD7six
AD7six

Reputation: 66258

When overriding a method call the parent

There are no details in the question but it's probable the new constructor that's been defined does not call the parent

i.e.

class Parent {

    protected $_name = '';

    public function __construct($name) {
        $this->_name = $name;
    }

    public function greet() {
        if (!$this->_name) {
            throw new Exception("I got no name");
        }
        return sprintf('Hi, I\'m %s', $this->_name);
    }
}

class Child extends Parent {

    public function __construct() {
        // some logic
    }
}

There are two errors in the above code example

  1. Unintentionally not calling the parent class
  2. Changing the method signature

The consequence of the first error is that this works:

$Parent = new Parent('Bob');
echo $Parent->greet();

Whereas this would throw an exception:

$Child = new Child('Boblini');
echo $Parent->greet();

Fixing the first problem alone will still cause an exception to be thrown, as the child constructor does not have the same arguments as the parent method, so it cannot pass the missing argument to the parent method.

Summary

  • Always call the overridden method (unless there's a specific reason not to)
  • Ensure the method signature is the same as the overridden method

Upvotes: 2

Related Questions