Suppose I have a static callable like \Foo::bar
.
I can assign this to a variable like this and then call it:
$myCallable = \Foo::class . '::bar';
// This works.
$myCallable('calling this works!');
But if I assign it to a static class property like this:
class MyClass {
function myFunc() {
static::$myCallable = \Foo::class . '::bar';
static::$myCallable('this does not work');
}
}
it fails, because it tries to call MyClass::Foo::bar()
.
Is there a way to fix this, other than using call_user_func()
?
Suppose I have a static callable like \Foo::bar
.
I can assign this to a variable like this and then call it:
$myCallable = \Foo::class . '::bar';
// This works.
$myCallable('calling this works!');
But if I assign it to a static class property like this:
class MyClass {
function myFunc() {
static::$myCallable = \Foo::class . '::bar';
static::$myCallable('this does not work');
}
}
it fails, because it tries to call MyClass::Foo::bar()
.
Is there a way to fix this, other than using call_user_func()
?
2 Answers
Reset to default 2It isn't mentioned in the Operator Precedence documentation but ::
seems to have lower precedence than function parenthesis. This should work:
(self::$myCallable)('this also works');
Full example:
class Foo
{
public static function bar(string $label): void
{
echo "Callable called: $label\n";
}
}
class MyClass
{
private static string $myCallable;
public function myFunc(): void
{
static::$myCallable = \Foo::class . '::bar';
(self::$myCallable)('this also works');
}
}
$myCallable = \Foo::class . '::bar';
$myCallable('calling this works!');
(new MyClass)->myFunc();
Demo
$myCallable('calling this works!');
^^^^^^^^^^^.. defined variable
now for your static:: invocation:
static::$myCallable('this does not work');
^^^^^^^^^^^.. undefined variable
(static::$myCallable)('this does work');
^^^^^^^^^^^^^^^^^^^.. defined static property
(static::$myCallable)(...)('this does work');
...
As you can see, it works the same, but you need a defined variable/property.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744922442a4601215.html
评论列表(0条)