【问题标题】:get_called_class in php 5.2*php 5.2 中的 get_call_class *
【发布时间】:2013-08-27 18:54:34
【问题描述】:

最近我完成了一个 php 版本为 5.3 的 web 项目,然后我将其上传到 php 版本为 5.2.* 的服务器。然后显示以下消息:

Fatal error: Class name must be a valid object or a string in /home/user_folder/public_html/_includes/class.myclass.php on line 264

在我的 class.myclass.php 中,我使用以下代码 ::

protected function get_table_value($record)  {
  $className = get_called_class();   //

  $object = new $className; // line 264
  // rest of the code
}

然后我将这段代码更改如下::

// get the database table's column's value
    protected function get_table_value($record)  {
       $className = $this->generate_class_name();
       $object = new $className;   // same error in this line

       // rest of code
    }

     private function generate_class_name()   {

        if ( !function_exists('get_called_class') ) {
           $bt = debug_backtrace();
           $l = count($bt) - 1;
           $matches = array();
           while(empty($matches) && $l > -1){
              $lines = file($bt[$l]['file']);
              $callerLine = $lines[$bt[$l]['line']-1];
              preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l--]['function'].'/',
              $callerLine,
              $matches);
            }
            if (!isset($matches[1])) $matches[1]=NULL; //for notices
              if ($matches[1] == 'self') {
              $line = $bt[$l]['line']-1;
              while ($line > 0 && strpos($lines[$line], 'class') === false) {
                 $line--;
             }
             preg_match('/class[\s]+(.+?)[\s]+/si', $lines[$line], $matches);
           }
         return $matches[1];               
        }   
        else {                
            return get_called_class();
        }            
    }

现在又来了 error msg。任何解决方案。

【问题讨论】:

    标签: php oop php-5.2


    【解决方案1】:

    您的问题不清楚。以下是手册的摘录:Get_Class(); 这会将您当前的类输入到作为 var 的 return 语句中(见图 2):

    图一

    class foo {
        function name()
        {
            echo "My name is " , get_class($this) , "\n";
        }
    }
    
    // create an object
    $bar = new foo();
    
    // external call
    echo "Its name is " , get_class($bar) , "\n";
    
    // internal call
    $bar->name();
    

    图2

    class foo{
      public function Test(){
        $Classname = get_class($this);
        $Instance = new $Classname;
        return $Classname;
      }
    }
    

    也许修改你的函数以遵循这个过程。

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2018-11-02
      • 2012-05-15
      • 2011-09-08
      • 2011-10-03
      • 2011-09-22
      相关资源
      最近更新 更多