CuriousMind
CuriousMind

Reputation: 34145

Partially override a function in php

Consider the following code:

class Manager{
  function a(){
    $var1 = 10;
    $var2 = 20;
    var_dump($var1 * $var2);
    echo "<br> var1=" . $var1 . "<br>";
    echo "var2=" . $var2;
  }
}

class Sub extends Manager{
  function a(){
    $var1 = 20;
    parent::a();
  }
}
$s = new Sub();
$s->a();

Here, I am trying to override the value of $var1 from Sub::a() then calling its parent function Manager::a(), hoping php will set $var1=20 & show result as 400(20 x 20). But it doesn't seem to work. $var1 is still equal to 10.

Wondering if there a way to to partially override a function in php where local variables of functions can be overridden? specifically in this code, how can I get out of 400, instead of current 200 ?

[Edit]

the Sub is just an example, I will have multiple child classes like Sub1, Sub2, Sub3 & so on. so the each sub-class will try to set different value for $value1, like this:

class Sub1 extends Manager{
      function a(){
        $var1 = 20;
        parent::a();
      }
    }

class Sub2 extends Manager{
      function a(){
        $var1 = 99;
        parent::a();
      }
    }
class Sub3 extends Manager{
      function a(){
        $var1 = 50;
        parent::a();
      }
    }

Upvotes: 1

Views: 1063

Answers (2)

bwoebi
bwoebi

Reputation: 23777

No. You can set a default function parameter, but you cannot override the local values of a function you call.

class Manager{
  function a($var1 = 10, $var2 = 20){ // default value of $var1: 10; of $var2: 20
    var_dump($var1 * $var2);
    echo "<br> var1=" . $var1 . "<br>";
    echo "var2=" . $var2;
  }
}

class Sub extends Manager{
  function a(){
    $var1 = 20;
    parent::a($var1); // you set $var1 parameter of function to 20; $var2 is set to the dafault value: 20
  }
}
$s = new Sub();
$s->a();

(btw. if you really want to redefine the function, you can use the runkit extension; but I wouldn't consider it.)


Also, when you have more subclasses, you can change them to match this format.

Upvotes: 3

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

Scope of the variables inside the class methods are always local. overwriting or calling parent method does not change anything.

I will prefer to use class property if i had to assign value dynamically and change it accordingly.

For example.

class Manager {

    protected $_var1;
    protected $_var2;

    function a() {
        $this->_var1 = 10;
        $this->_var2 = 20;
        var_dump($this->_var1 * $this->_var2);
        echo "<br> var1=" . $this->_var2 . "<br>";
        echo "var2=" . $this->_var2;
    }
}

class Sub extends Manager {
    function a() {
        $this->_var1 = 20;
        parent::a();
    }
}

$s = new Sub();
$s->a();

This will overwrite the values and work the way you expect it to.

Hope this helps.

Upvotes: 3

Related Questions