Sebin P Johnson
Sebin P Johnson

Reputation: 71

access parent method from child object with attributes in php?

I have the following PHP classes:

class a {
    public function vw($xc) {
        return $xc;
    }
}

class b extends a {
    public function wv() {
        echo vw() . 'from b via wv';
    }
}

$d = new a;
echo $d->vw('this is a');
$c = new b;
echo $c->vw('this is a from b via a');
$c->wv();

The output I am getting is:

   this is a

Why am I not getting the outputs of echo $c->vw('this is a from b via a'); and c->wv(); ?

Upvotes: 1

Views: 60

Answers (3)

Charlotte Dunois
Charlotte Dunois

Reputation: 4680

You can access a parent's method via parent::, e.g. parent::vw(). But the method vw of class a expects a parameter, so this code snippet won't work at all. But you should get the idea of using the parent keyword.

class a {
    public function vw($xc) {
        return $xc;
    }
}

class b extends a {
    public function wv() {
        echo parent::vw() . 'from b via wv';
    }
}

$d = new a;
echo $d->vw('this is a');
$c = new b;
echo $c->vw('this is a from b via a');
$c->wv();

http://php.net/manual/en/keyword.parent.php

https://3v4l.org/0MkQI

Upvotes: 2

yanick
yanick

Reputation: 17

Try this

        class a { 
            public tt;

               public function vw($xc){
                   $this->tt = $xc;
            return $this->tt;
        }
}

class b extends a
{
   public function(){
   return $this->tt. 'from b via wv'
}
}

Upvotes: 0

Giovanni S. Fois
Giovanni S. Fois

Reputation: 79

In the class "b", you should write the function vw as:

   public  function wv(){
     echo $this->vw() . "from b via wv\n";
   }

Besides, in your last line the call of $c->wv() lacks a parameter: $c->wv("I'm a missing parameter");

Upvotes: 0

Related Questions