问题
I understand that PHP doesn't allow me to create a new instance of ClassB inside my ClassA, if the creation is not inside the scope of a function. Or I just don't understand...
class ClassA {
const ASD = 0;
protected $_asd = array();
//and so on
protected $_myVar = new ClassB(); // here I get *syntax error, unexpected 'new'* underlining 'new'
// functions and so on
}
Do I need some kind of constructor, or is there a way to actually create the object instance in a free way as I desire, as I am used to do in Java or C#. Or is using Singleton the only closest solution to my approach?
P.S. ClassB is located in the same package and folder as ClassA.
回答1:
According to the PHP docs:
declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
As such, you will need to instantiate $_myVar
in your constructor:
protected $_myVar;
public function __contruct() {
$this->_myVar = new ClassB();
}
回答2:
Yes, there is a constructor (see below)
class ClassA {
const ASD = 0;
protected $_asd = array();
//and so on
protected $_myVar; // initialization not allowed directly here
public function __contruct() {
$this->_myVar = new ClassB();
}
}
来源:https://stackoverflow.com/questions/19793586/create-new-object-in-php