Jump to content

[SOLVED] Calling variables in an extended class.


noidtluom

Recommended Posts

I'm trying to do this:

 

<?php

  class foo
  {
    protected $asdf;
    
    public function __construct()
    {
      $this->asdf = 'lol';
    }
    
  }
  
  class bar extends foo
  {
    public function __construct()
    {
      echo $this->asdf;
    }
  }

?>

 

How can it be done?

code for u

 

<?php

  class foo
  {
    protected $asdf;
    
    public function __construct()
    {
      $this->asdf = 'lol';
    }
    
  }
  
  class bar extends foo
  {
    public function __construct()
    {
      parent::__construct();
      echo $this->asdf;
    }
  }

?>

No. But you set asdf within the __construct of the parent, but the parents __construct is not called automatically when a child is instantiated.

 

If you simply had...

 

<?php

  class foo
  {
    protected $asdf = 'lol';    
  }
  
  class bar extends foo
  {
    public function __construct()
    {
      echo $this->asdf;
    }
  }

?>

 

That would work fine.

Ok. Thanks.

Glad I sorted out those principles. Alright, so how would I get this to work?

 

<?php

  class foo
  {
    protected $asdf;
    
    public function test($var)
    {
      $this->asdf = $var;
    }    
  }
  
  class bar extends foo
  {
    public function anothertest()
    {
      echo $this->asdf;
    }
  }

  $foo = new foo();
  $foo->test('lol');
  
  $bar = new bar();
  $bar->anothertest();

?>

 

(It's a simplified version of the code I'm working on)

I think you misunderstand inheritance.

 

There you have created 2 DIFFERENT objects, one of type foo and another of type bar. Inside foo there is a variable called asdf, by calling test('lol') you are setting asdf inside foo ONLY to 'lol'. Now inside bar you also have a variable called asdf, which when you do $bar = new bar() is set to nothing (null), you then call anothertest() which grabs that internal variable from $bar and echo's it. It's value is null there nothing is output.

 

What you really want to do is :

 

$bar = new bar();

$bar->test('lol');

$bar->anothertest();

 

How does this work?

the bar class inherited the method test(). Understand any better now?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.