Page 1 of 1

New Help With the [new] operator in a Class Object

Posted: Wed Nov 19, 2014 7:47 am
by PHPHelpNeeded
This is my code:

------------------------------------------------------------

Code: Select all

	class ClassB {

		private $obj = new ClassA();

	} //end of ChessBlock
----------------------------------------------------------------

In my php IDE, Eclipse, why am I getting syntax error from using the keyword [NEW] to created a new instance object of ClassA as a private object inside ClassB?

it says, "syntax error, unexpected new"

Any help please.

Re: New Help With the [new] operator in a Class Object

Posted: Wed Nov 19, 2014 7:54 am
by Celauran
http://php.net/manual/en/language.oop5.properties.php

Property initializations must use a constant value. For what you're trying to do, assign the value of $obj inside the constructor, either by instantiating ClassA in the constructor or, better, by injecting it into the constructor.

Re: New Help With the [new] operator in a Class Object

Posted: Wed Nov 19, 2014 7:56 am
by Celauran

Code: Select all

<?php

class ClassB {
	private $obj;

	public function __construct() {
		$this->obj = new ClassA();
	}
}
$b = new ClassB();

// Better

class ClassC {
	protected $obj;

	public function __construct(ClassA $obj) {
		$this->obj = $obj;
	}
}
$a = new ClassA();
$c = new ClassC($a);