1

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

2
  • 1
    $this is not defined when class variables are declared. After __construct is called you can access $this Commented Jun 25, 2014 at 13:23
  • It's true that can not use $this if class members are not declared. __construct seems the best solution. But I'm trying to use const instead of normal variable. Commented Jun 25, 2014 at 14:01

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

2 Comments

You can't. You're only allowed to assign a constant value directly after declaration. But a variable value (what you are trying) is not allowed. That is were the constructor is designed for. More about it can be found here: php.net/manual/en/language.oop5.properties.php
You're right. The best solution is using constructor.
1

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());

1 Comment

You can find some info from php manual. Take a look : php.net/manual/en/language.oop5.properties.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.