在 PHP 中创建新对象


create new object in php

我知道PHP不允许我在ClassA中创建ClassB的新实例,如果创建不在函数范围内。或者我只是不明白...

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# 中习惯的那样。还是使用单例是唯一最接近我的方法的解决方案?

P.S. ClassB 与 ClassA 位于同一个包和文件夹中。

根据 PHP 文档:

声明可以包括初始化,但此初始化必须是常量值,也就是说,它必须能够在编译时进行评估,并且不得依赖于运行时信息才能进行评估。

因此,您需要在构造函数中实例化$_myVar

protected $_myVar;    
public function __contruct() {
   $this->_myVar = new ClassB();
}

是的,有一个构造函数(见下文)

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();
        }
    }