create new object in php

放肆的年华 提交于 2019-12-11 04:27:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!