Skip to content
Advertisement

call methods and objects using php

i have this code :

   <?PHP
 function call_and_set( $obj, $txt){
                         return call_user_method('example', $obj, $txt);
                    }

        class test{

                function example($text){
                        echo $text;
                    }

            }
            $test = new test();
       call_and_set($test, "Hello World!");
    ?> 

in my code i don’t always want to use

$test = new test ….

I want to use the name directly instead of $test. For example:

call_and_set("test", "Hellow World!").

Advertisement

Answer

You should use a factory method pattern or something like that. With a factory method you can create a class based on a string. In PHP it’s not that hard. Try something like this:

<?PHP

    function call_and_set( $className, $txt) {
         $obj = ProductFactory::create($className);
         return call_user_method('example', $obj, $txt);
    }

    class test
    {

        function example($text){
            echo $text;
        }

    }
            
    class ProductFactory
    {
        public static function create($className) {
            //Add some checks and/or include class files
            return new $className();
        } 
    }           
            
    call_and_set("test", "Hello World!");
?> 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement