0

I try to create object in PHP class, but i get some interesting errors in IDE, like unexpected ( token etc. Here is my code:

class A {
  public $a = 1;
}

class B {
  $aa = new A(); 
}

Where is the problem?

2
  • 4
    Properties can only be initialized with a fixed value (as that int). If you want it to have the value of a function or be an object, assign that in the constructor or any other method Commented Oct 22, 2014 at 18:10
  • @kingkero: Answer it. Commented Oct 22, 2014 at 18:14

3 Answers 3

3

In PHP, you can only assign "fixed" values to properties in the class definition.

class A {
    public $a = 3; // will work
    public $b = "hello"; // will work
    public $c = foo(); // won't work
    public $d = new Foo(); // won't work
}

If you want to do so, you can use the __construct() method which will be called every time a new instance is created or any other method that you call.

class B {
    public $aa; // define visibility of $aa
    function __construct() {
        $this->aa = new A();
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You need to make a constructor on class A

class A {
    function __construct() {
        $this->a = 1;
    }

    public function returnA() {
        return $this->a;
    }
}

$aa = new A();
echo $aa->returnA();

Comments

-1

Try to create a constructor in class A and see if it works:

class A {
  public $a;

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

}

class B {
  $aa = new A(); 
}

Comments

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.