Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stdClass and anonymous function

Tags:

php

stdclass

I can do this with anonymous function

 $func = function() {
      return "Hello World";
 };
 var_dump($func());

However, I cannot do this

$namespace->func = function() {
      return "Hello World";
 };
 var_dump($namespace->func());

I will get this error

Call to undefined method stdClass

The workaround that I have discovered so far is to use another variable

$temp = $namespace->func;
var_dump($temp());

Is there a way that I can do it in one line?

like image 944
invisal Avatar asked Jul 10 '26 07:07

invisal


1 Answers

You can use __invoke() :

// declare $namespace to be conform to strict standards
$namespace = new StdClass();

$namespace->func = function() {
      return "Hello World";
 };
var_dump($namespace->func->__invoke());

That's because even if a property func exists which is a closure, PHP will not check if it is a closure and call it.

like image 79
hek2mgl Avatar answered Jul 11 '26 22:07

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!