在php中创建新对象 [英] create new object in php

查看:57
本文介绍了在php中创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道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文档:

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

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.

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

As such, you will need to instantiate $_myVar in your constructor:

protected $_myVar;    

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

这篇关于在php中创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆