2

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?

2
  • 2
    Properties must only be assigned a constant expression. To do what you want there you do it in the __construct(). Commented Oct 3, 2016 at 19:36
  • 1
    Side note, if your myClass2 is in a separate file, be sure to include the file containing the myClass1. Commented Oct 3, 2016 at 19:39

1 Answer 1

5

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();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you a lot! This totally perfectly answered my question! Maybe, if i may, one more stupid question there: What is the reason behind this language-feature?
because php can't time travel. consider something like public $foo = $GLOBALS['bar']. Whatever code created that global $bar variable may not have executed yet, so what value should get assigned to $foo? Once you do a variable assignment, there's no "memory" of where the value you assigned came from, and PHP will not retroactively "fill in" placeholder values. or maybe you have public $foo = file_get_contents('file that doesn't exist yet').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.