James Brooks
James Brooks

Reputation: 1311

PHP Variable from extended class

I'm trying to retrieve a variable from an extended class. This is how my main class looks:

class SS {
    public $NONE = NULL;
    public $NUMBERS = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
    public $OPERATORS = array("=", "&&", ">", "<", "+", "-", "/", "*", "^");
    public $DBLQUOTES = '"$1"';
    public $SNGQUOTES = "'$1'";
    public $CODE;

    function SuperSyn($sCode, $cLang) {         
        $hLang = new VB6;
        $VB6 = $hLang->__construct();
        echo $VB6->ssAuthor;
    }
}

And my extended class looks like this (I've removed many of the keywords).

class VB6 extends SS {
    public function __construct() {
        $ssAuthor = "James Brooks";
        $ssCSS = "languages/vb6.css";
        $ssNumbers = $NUMBERS;
        $ssKeywords = array("Abs", "Access", "AddItem");
        $ssReserved = $NONE;
        $ssComments = "('.+)";
        $ssOperators = $OPERATORS;
        $ssDoubleQuote = $NONE;
        $ssSingleQuote = $NONE;
    }
}

If I remove the public function __construct being called, PHP bitches that it's expecting a function.

My question is, how can I retrieve a variable from the extended class into my main class?

Upvotes: 1

Views: 6072

Answers (4)

J&#246;rg
J&#246;rg

Reputation: 946

I think that there's a logical problem with your expectiation. Why should a function of the class SS know about a variable that only exists in the VB6 subclass?

That would not be a clean inheritance behaviour and reveals a problem with your classes.

Two choices to solve that:

  • Put the variable in the main class to use it in a function in that class
  • Put the function using the subclass's variable inside the subclass

(After reading the comments about the parent keyword and ´$this´ variable: I understood the question differently and don't think either of those to would help since the opposite direction is required: parent class function > subclass variable, not subclass function > parent class variable)

Upvotes: 0

Tom Haigh
Tom Haigh

Reputation: 57815

The constructor will be called for you when you create an object, so this should work:

function SuperSyn($sCode, $cLang) {                     
     $hLang = new VB6(); //I think you need some parameters here
     echo $VhLang->ssAuthor;
}

However in your VB6 constructor you are currently only assigning local variables, so you wouldn't be able to access ssAuthor externally. Instead you probably want to do something like:

class VB6 extends SS {
    public $ssAuthor;

    public function __construct() {
        $this->ssAuthor = "James Brooks";
        //etc.
    }
}

Upvotes: 1

knittl
knittl

Reputation: 265211

use parent:: or $this-> (depends, i.e. you have two variables with the same name)

Upvotes: 0

KB22
KB22

Reputation: 6969

Use php's parent keyword.

PHP parent

Upvotes: 1

Related Questions