Edwin Rodríguez
Edwin Rodríguez

Reputation: 1257

Calling function in static member variable

I'm trying to call a function in a static class variable but I have some problems

This is the minimal example

 #!/usr/bin/php
<?php

class Foo {
  public static $func;

  public static function call() {
    echo "calling func\n";
    if ( is_callable(self::$func))
      self::$func();
    else echo "no call\n";
  }
}


Foo::call();

Foo::$func = function() { echo "hello\n"; };

Foo::call();

?>

It gives me the following output

calling func
no call
calling func
PHP Notice:  Undefined variable: func in /home/edwin/hola.php on line 10
PHP Fatal error:  Function name must be a string in /home/edwin/hola.php on line 10

Upvotes: 0

Views: 39

Answers (1)

Federkun
Federkun

Reputation: 36944

Store a reference of self::$func in a variable:

public static function call() {
    echo "calling func\n";

    $callable = self::$func; // store in a variable
    if ( is_callable($callable))
        $callable();
    else
        echo "no call\n";
}

Upvotes: 1

Related Questions