4

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.

3
  • Does your example throw an error? What is the valid of $_POST['class']? Commented Oct 26, 2009 at 19:36
  • It's 5.2.1. I get the following error: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM Commented Oct 26, 2009 at 19:42
  • For the record, "Paamayim Nekudotayim" is Hebrew for "double colon". Commented Oct 26, 2009 at 20:02

5 Answers 5

8

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).

Sign up to request clarification or add additional context in comments.

Comments

2

What you have works as of PHP 5.3.

ps. You should consider cleaning the $_POST['class'] since you cannot be sure what will be in it.

Comments

1

use call_user_func

heres an example from php.net

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

1 Comment

It would be good add this piece of code outside to abstract so much spaguetti. +1 anyway
0

I believe this can only be done since PHP 5.3.0. Check this page and search for $classname::$my_static to see the example.

Comments

-2

I may be misunderstanding what you want, but how about this?

switch ($_POST['ClassType']) {
    case "Class1":
        $class1::create();
        break;
    case "Class2":
        $class2::create();
        break;
    // etc.
}

If that doesn't work, you should look into EVAL (dangerous, be careful.)

Comments

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.