views:

155

answers:

4

Hi,

I currently have two classes, one called Dog, one called Poodle. Now how can I use a variable defined in Dog from the Poodle class. My code is as follows:

  class dog {
       protected static $name = '';

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

  class Poodle extends dog {
       function __construct($name) {
           parent::__construct($name)
       } 

       function getName(){
           return parent::$name;
       }
  }

$poodle = new Poodle("Benjy");
print $poodle->getName();

I get this error

Notice: Undefined variable: name

A: 

Oooops sorry guys, i missed that little bit out of my code when i was posting it on here. it still doesnt work with extends in

Matt
+2  A: 

The problem is in your Dog constructor. You wrote:

$this->name = $name;

But using $this implies that name is an instance variable, when in fact it's a static variable. Change it to this:

self::$name = $name;

That should work fine.

VoteyDisciple
+1, you are right.
Ionuț G. Stan
However it doesn't make much sense to have all (inherented) instances of dog to have the same name, so static doesn't make much sense here.
Pim Jager
A: 

In your dog class you have declared the variable $name as static, you have to declare the variable without the static word

class dog {
   protected $name = '';

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



class Poodle extends dog {
   function __construct($name) {
       parent::__construct($name)
   } 

   function getName(){
       return $this->name;
   }
}

$poodle = new Poodle("Benjy");
print $poodle->getName();
Juraj Blahunka
+5  A: 

i guess 'name' is an attribute of the concrete Dog, so it shouldn't be static in the first place. To access non-static parent class attributes from within an inherited class, just use "$this".

 class dog {
    protected $name = '';

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

 class Poodle extends dog {
    function getName(){
     return $this->name;
    }
 }
stereofrog