php - How to invoke a callable stored inside a static property? - Stack Overflow

Suppose I have a static callable like Foo::bar.I can assign this to a variable like this and then cal

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()?

Share edited Mar 8 at 0:39 Dharman 33.5k27 gold badges101 silver badges149 bronze badges Recognized by PHP Collective asked Mar 7 at 14:53 joachimjoachim 31k13 gold badges45 silver badges50 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

It 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信