简体   繁体   中英

Can a PHP function return a reference to a static object?

Say I have a static object:

class everything{
    public static function must(){
        return "go!";
    }
}

When I do this:

echo everything::must();

I get the response:

go!

Which is the expected behavior.


Now, for my own reasons (legacy code support) I'd like to be able to call that static object from the return of a function call, in a syntax similar to this:

print accessorFunction()::must(); // Or something as close to it as possible

function accessorFunction(){
    returns (reference to)everything; // Or something as close to it as possible
}

I hope I've made the question clear enough.

Thanks.

I'm not sure if this is the kind of reference you're looking for, but you can always do:

print call_user_func( array( accessorFunction(), "must"));

function accessorFunction(){
    return 'everything';
}

You could also use variable classes:

function accessorFunction() {
    return new everything();
}

$class = accessorFunction();
echo $class::must(); // go!

It's NOT possible to call static methods this way:

print accessorFunction()::must();

But possible

$class_name = accessorFunction();
print $class_name::must();

Documentation - http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php

I think the cleaner option would be to mix @nickb and @GeorgeBrighton solutions:

function accessorFunction() {
    return 'everything';
}

$class = accessorFunction();
echo $class::must(); // prints go!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM