1

I am reading the documentation of php about Variable functions

I don't understand the example 4 below.

How come the first and second $func(); can call the function bar() and baz(). The $func is a array.

Maybe it is a silly question. Thanks.

<?php
class Foo
{
    static function bar()
    {
        echo "bar\n";
    }
    function baz()
    {
        echo "baz\n";
    }
}

$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar"
?>

1 Answer 1

2

Have a look at the documentation of callables - if an array is used, the first element references the class name to be used, the second element references the method name to be called. This means, the two last lines are equal:

$func = array("Foo", "bar");

$func(); // prints "bar"
Foo::bar(); // also prints "bar"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it would be better if the callables are mentioned in the vairable functions example as a reference. Also, the callables documentation doesn't have examples like $func().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.