【问题标题】:call methods and objects using php使用php调用方法和对象
【发布时间】:2014-09-13 15:18:20
【问题描述】:

我有这个代码:

   <?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!");
    ?> 

在我的代码中我并不总是想使用

$test = 新测试 ....

我想直接使用名称而不是$test。例如:

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

【问题讨论】:

    标签: php oop callback


    【解决方案1】:

    我不知道他们为什么不给你投票。我认为这个问题并没有那么糟糕。

    您应该使用工厂方法模式或类似的东西。使用工厂方法,您可以创建基于字符串的类。在 PHP 中,这并不难。试试这样的:

    <?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!");
    ?> 
    

    【讨论】:

      【解决方案2】:

      我想我了解您要完成的工作,但有点不清楚。您可以将要实例化的类的名称指定为变量名:

      <?php
      
      class test {}
      
      $test = 'test';
      
      $testObj = new $test;
      

      在尝试实例化之前验证类是否存在可能是个好主意,但是:

      if(class_exists($test)) {
          $testObj = new $test;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-09-28
        • 1970-01-01
        • 2012-07-15
        • 2010-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-18
        相关资源
        最近更新 更多