Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to extended PHP class

Tags:

oop

php

I've been using OOP in PHP for a while now, but for some reason am having a total brain meltdown and can't work out what's going wrong here!

I have a much more complex class, but wrote a simpler one to test it, and even this isn't working...

Can anyone tell me what I'm doing wrong?

class test
{
    public $testvar;

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

class test2 extends test
{
    function __construct()
    {
        echo $this->testvar;
    }
}

$test = new test;
$test2 = new test2;

All I'm trying to do is pass a variable from the parent class to the child class! I swear in the past I've just used $this->varName to get $varName in the extension??

Thanks!

like image 985
Matt Avatar asked Sep 19 '09 21:09

Matt


1 Answers

You have to call the constructor of the parent class from the constructor of the child class.

Which means, in your case, that your test2 class will then become :

class test2 extends test
{
    function __construct()
    {
        parent::__construct();
        echo $this->testvar;
    }
}

For more informations, you can take a look at the page Constructors and Destructors of the manual, which states, about your question :

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.


You can use $this->varName : this is not a problem ; consider this code :

class test {
    public $testvar = 2;
    function __construct() {
       $this->testvar = 1;
    }
}
class test2 extends test {
    function __construct() {
        var_dump($this->testvar);
    }
}
$test2 = new test2;

The output is :

int 2

Which is the "default" value of $testvar.

This means the problem is not that you cannot access that property : the problem, here, is only that the constructor of the parent class has not been called.

like image 125
Pascal MARTIN Avatar answered Sep 22 '22 16:09

Pascal MARTIN