PHP How to access variable from other variable inside class?

Here is my class:

<?php
class myClass {
    private $a = 1;
    private $b = array(
        'a' => $this->a
    );

    public function getB() {
        return $this->b;
    }
}

$myclass = new myClass();
var_dump($myclass->getB());

I want to access variable $a in variable $b. But this shows this error:

( ! ) Parse error: syntax error, unexpected '$this' (T_VARIABLE) in C:\xampp\htdocs\test1.php on line 5

Upvotes: 1

Views: 116

Answers (2)

Gladen
Gladen

Reputation: 802

You are not allowed to assign a variable property this way. The best way is to probably assign the variable to the array in the constructor instead. So, like this:

<?php
class myClass {
    private $a = 1;
    private $b = array();

    public function __construct() {
        $this->b['a'] = $this->a;
    }

    public function getB() {
        return $this->b;
    }
}

$myclass = new myClass();
var_dump($myclass->getB());

Upvotes: 2

onuri
onuri

Reputation: 170

You can access variables by constructor.

Here is some code:

class myClass {
    private $a;
    private $b;

    public function __construct(){
        $this->a = 1;
        $this->b = array('a'=>$this->a);
    }

    public function getB() {
        return $this->b;
    }
}

$myclass = new myClass();
var_dump($myclass->getB());

Upvotes: 1

Related Questions