简体   繁体   中英

How to use a php class in another class

I searched for answers a lot, but only found stuff around questions of whether one can write a class in another class and stuff like that.

So there is the first document, which is:

Document1:

class MyClass1 {

    private $myAttribute1;
    __construct(){
        this->myAttribute1 = 'blabla';
    }
}

now calling in the same document

$myObject1 = new MyClass1();

works totally fine in NetBeans.

Meanwhile when I build another document, lets call it Document2, and build another class there, which is intended to use MyClass1 , Netbeans tells me there is a problem:

Document2:

myClass2 {
    $myAttribute2 = new myClass1(); 
}

so this does not work in my NetBeans, just tells me 'unexpected new'. How can I use MyClass1 in myClass2 since this way does not work?

PHP only allows certain expressions to be used as initializer values for class attributes:

class foo {
    $x = 7; //fine, constant value
    $y = 7+7; // only fine in recent PHPs
    $z = new bar(); // illegal in all PHP versions
}

The 7+7 version was only supported in recent PHP versions, and the ONLY expressions allowed are those whose resulting value can be COMPLETELY calculated at compile-time. Since the new cannot be executed at compile time, only at execution time, it's an outright permanently illegal expression.

That means for "complex" expressions, which can only be calculated at runtime, you have to do that expression in the constructor:

class foo {
    public $z;
    function __construct(){ 
         $z = new bar();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM