Reputation: 919
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?
Upvotes: 2
Views: 76
Reputation: 360572
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();
}
}
Upvotes: 5