问题描述
我知道PHP不允许我在ClassA内创建ClassB的新实例(如果创建的内容不在函数范围之内).还是我不明白...
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
}
我是否需要某种构造函数,或者是否有一种方法可以像我过去在Java或C#中那样随意地以自由方式实际创建对象实例.还是使用Singleton是最接近我方法的解决方案?
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与ClassA位于相同的程序包和文件夹中.
P.S. ClassB is located in the same package and folder as ClassA.
推荐答案
根据 PHP文档:
因此,您将需要在构造函数中实例化$_myVar
:
As such, you will need to instantiate $_myVar
in your constructor:
protected $_myVar;
public function __contruct() {
$this->_myVar = new ClassB();
}
这篇关于在php中创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!