繁体   English   中英

PHP:使用变量名称在Singleton Object上调用静态函数

[英]PHP: Use variable name to call static function on Singleton Object

我需要使用Singleton设计从对象调用静态函数,但要使用变量作为类名。

最好的方法, $class::getInstance(); ,仅在PHP 5.3中可用,而我找到的另一种方法是call_user_func(array($class, 'getInstance')); ,导致最长执行时间被破坏。 有谁知道为什么发生这种情况,或者有什么办法可以解决这个问题?

我知道这不是完成任务的最佳方法,并且Singleton设计模式不是我的首选,但是不幸的是,这不取决于我。

在此先感谢任何贡献的人:)

我包括了其余的代码:

abstract class Library
 {
  protected function __construct(){}
  final private function __clone(){}

  final public static function &getInstance()
   {
    static $libs = array();
    $lib = get_called_class();
    if(!isset($libs[$lib])) $libs[$lib] = new $lib();
    return $libs[$lib];
   }

 }

public function &loadLibrary($lib)
 {
  // Filter $lib, and load the library class file...
  // Following only works in PHP 5.3
  //   return $lib::getInstance();
  // Following results in maximum execution time being breached.
   return call_user_func(array($lib, 'getInstance'));
  }
}

$someLibrary =& loadLibrary('someLibrary');

someLibrary.php:

class someLibrary extends Library
 {
  protected function __construct(){}
  // Code...
 }

Soulmerge提出了一个正确的观点,说get_called_class()仅在PHP 5.3中,因此我必须使用它,但是, get_called_class() ,我只是get_called_class()一样欺骗自己(谢谢http: //www.Chris Webb 。 septuro.com/获取代码-太复杂了,无法依靠我自己编写!)。

if(!function_exists('get_called_class'))
 {
  class classTools
   {
    static $i = 0;
    static $fl = null;
    static function get_called_class()
     {
      $bt = debug_backtrace();
      if(self::$fl == $bt[2]['file'].$bt[2]['line']) self::$i++;
      else {
       self::$i = 0;
       self::$fl = $bt[2]['file'].$bt[2]['line'];}
      $lines = file($bt[2]['file']);
      preg_match_all('/([a-zA-Z0-9\_]+)::'.$bt[2]['function'].'/', $lines[$bt[2]['line']-1], $matches);
      return $matches[1][self::$i];
     }
   }
  function get_called_class()
   {
    return classTools::get_called_class();
   }
 }

我将再次遍历所有代码,因为必须在某处循环。 回到绘图板上:

您应该首先确定使您陷入无限循环的原因。 例如,您的构造函数( someLibrary::__construct() )是否具有直接/间接调用Library::getInstance()任何代码?

EDIT get_called_class()是PHP 5.3中引入的,因此,如果您的代码实际get_called_class() ,则您已经在运行5.3

您可以尝试使用eval()解决此问题。

让您有个想法:

$theVar = "relvantClassName";
$someObject = eval($theVar::getInstance());
$result = $someObject->performAction();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM