Extract object's functions to global functions

192
January 25, 2017, at 01:33 AM

So I have this class:

class MyClass {
    public static function printMessage($text) {
        echo $text;
    }
}

And I would like to use it in these ways:

MyClass::printMessage('test'); // test
printMessage('test'); // test

So printMessage will work as a method and also as a function. Is something like that possible with PHP? (Something like autoload for classes) I cannot find a good solution or even answer - no. It is not necessary for me, I'm just curious so I don't need to write same function structure twice. I know I can use code like public static function printMessage($text) { return printMessage($text); }, but it's not what I'm looking for.

Answer 1

You could either use a wrapper:

public function printMessage($text){
    MyClass::printMessage($text);
}

Or declare the function as global, which does not seem to be what you're looking for.

Answer 2

You can map/wrap your class function into global function:

function printMessage($string){
    MyClass::printMessage($string);
}

But Is something like that possible with PHP? Nope. A function call MUST be unique in PHP.

You can also do this:

$printMessage = function($string ){MyClass::printMessage($string);};

to get an shorthand $printMessage($string);

But best is to avoid global functions overall. And if you are going next level coding, then static class methods should avoided too.

READ ALSO
Wordpress posts page for customer filtering and sorting along with category filter

Wordpress posts page for customer filtering and sorting along with category filter

I am new to wordpress development and have been struggling to implement WordPress posts (events) list page with following functionality - Category filtering - Past event or Future event or Current event - Sort by event start date or event end date

184
Get index # of array in twig

Get index # of array in twig

Trying to output the index # of an array in twig, having trouble finding it in the docsAnyone know how to get it?

863
Elasticsearch query with multiple attributs and values

Elasticsearch query with multiple attributs and values

I try to construct, in php, an query with different attribut: this following code work :

229