William
William

Reputation: 83

PHP inherit method which return $this;

I am searching for the correct way to the next code in PHP:

class X {
    var $A = array();

    function Y() {
        $this->A[] = array('price'=>1);
        return $this;
    }
}

class Y extends X {

    var $VAT = 1.27;

    function Y() {

        parent::Y(); //at this point what is the correct way to call parent method?

        foreach ($this->A AS $akey => $aval) {
            if (is_array($aval)&&(array_key_exists('price',$aval))) {
                $this->A[$akey]['price'] = $aval['price'] * $this->VAT;
            }
        }
        return $this;
    }
}

When I call parent method with "parent::Y();" I think this will not the correct way in PHP because it will return with an object which not ordered to any variable identifier and may cause a warning or a notice in error log.

Have anybody a good advice for what is the correct way to call method in this situation - Without modifying class X?

Upvotes: 0

Views: 64

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

If you need to call parent method you can simply do it without a problem using parent::method_name().

As in this case $A property is public (var used) it will be visible also in child class.

You don't need to worry that method Y returns $this. It's used probably for chaining class methods and you don't use it here so you don't need to care about it.

Upvotes: 1

EricSchaefer
EricSchaefer

Reputation: 26410

The method is fine as it is. No need to assign the result of parent::Y() to a variable.

Upvotes: 0

Noy
Noy

Reputation: 1268

As far as the official documentation goes, parent::method(); is the way to go.

Upvotes: 0

Related Questions