3 ms·
With arrays you would have to do: $o = (object)[ 'foo' => 'bar' ]; Personally I think there should be a way to create objects right away inste
by yogo 14y ago
With arrays you would have to do:
$o = (object)[
'foo' => 'bar'
];
Personally I think there should be a way to create objects right away instead of having to cast an array. Maybe there is a good reason all together for not using objects but I very much prefer typing $var->field instead of $var['field'].
- brokenparser 14y agoSure, but this still doesn't work: $o = (object)[ 'foo' => function(){ print 'bar'; }, ]; $o->foo(); You have to do it this way: call_user_func($o->foo); Or this way: $foo = $o->foo; $foo(); Which doesn't work when foo is defined as a class method.
- yogo 14y agoI believe by design it will always be: $foo = $o->foo; $foo(); Using __get/__set behaves the same way. Let's say $o is of SomeType that defines those magic methods. You can have a function foo on that type that is defined as a public method. $o->foo(); // the actual instance method $o->foo = function() { print 'bar'; }; $o->foo(); // same instance method $foo = $o->foo; $foo(); // prints bar In the case of StdClass it might be possible to do it your way where foo could be callable ($o->foo()) but I can see why they wouldn't allow this in order to keep things consistent. Edit: It also behaves the same way if you assign a function to a public field of a class (I'm using 5.4) so I actually support not allowing a method to be directly callable in this fashion because this would be the only case where this behavior would occur.