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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
PHPHelpNeeded
Forum Commoner
Posts: 83
Joined: Mon Nov 17, 2014 8:03 pm

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

Post 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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post 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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post 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);
Post Reply