Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Using a variable when calling a static method

I have three classes that all have a static function called 'create'. I would like to call the appropriate function dynamically based on the output from a form, but am having a little trouble with the syntax. Is there anyway to perform this?

$class = $_POST['class'];
$class::create();

Any advice would be greatly appreciated.

Thanks.

like image 886
Dan Avatar asked Jan 23 '23 02:01

Dan


1 Answers

If you are working with PHP 5.2, you can use call_user_func (or call_user_func_array) :

$className = 'A';

call_user_func(array($className, 'method'));

class A {
    public static function method() {
        echo 'Hello, A';
    }
}

Will get you :

Hello, A


The kind of syntax you were using in your question is only possible with PHP >= 5.3 ; see the manual page of Static Keyword, about that :

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

like image 120
Pascal MARTIN Avatar answered Feb 01 '23 04:02

Pascal MARTIN