在PHP> = 4.3.0中使用静态属性?

med*_*iev 5 php php4 static-members

免责声明:是的,我被迫支持PHP 4.3.0.我知道它已经死了.不,我不能升级它,因为我正在处理多个服务器,其中一些我没有su访问权限.

好吧,因为我不能使用,self::因为它是PHP5特定的,我应该如何在PHP4类中实现静态?到目前为止,我的研究似乎我至少可以使用static关键字除了只在函数上下文中,我已经看到另一种方法使用$ _GLOBALS,但我不认为我将使用它.

就这样我们在同一页面上我需要访问4中的这些PHP5静态:

public static $_monthTable = array(
     31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
public static $_yearTable = array(
     1970 => 0,            1960 => -315619200);
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经提出了我自己的函数,基本上设置一个静态变量,如果找不到,我将所有静态属性硬编码到其中.但是,我不完全确定如何在同一类中的anther方法中引用这些静态,假设它没有被实例化并且没有触发构造函数,这意味着我无法使用$this.

class DateClass {

    function statics( $name = null ) {

        static $statics = array();

        if ( count( $statics ) == 0 ) {
            $statics['months'] = array(
                'Jan', 'Feb'
            );
        }

        if ( $name != null && array_key_exists($name, $statics ) ) {
            return $statics[$name];
        }
    }

};

var_dump( DateClass::statics('months') );
Run Code Online (Sandbox Code Playgroud)

问题1:这可行吗?我应该尝试使用其他方法吗?

问题2:我如何从同一个类的方法中引用静态?我试过,__CLASS__::statics但我认为__CLASS__只是一个字符串,所以我不是真的调用一个方法.

注意:我将把它实现到一个框架中,该框架将用于Apache2 +/IIS6 +,PHP4.3.0到PHP 5.2,OSX/Linux/Windows.

fre*_*sch 4

回答你的第一个问题,我认为你的解决方案很好。我会扩展它,以便也可以设置和取消设置变量。我还会以不同的方式“启动”静态 $statics,未设置变量的值默认为null.

<?php
class DateClass {
  function statics( $name, $value=null, $unset=null ) {
    static $statics;
    // better way to "prime" $statics, it's null by default
    if ( !$statics ) {
      $statics = array( "months" => array( "Jan", "Feb" ) );
    }
    if ( $value )
      $statics[ $name ] = $value;
    if ( $unset )
      unset( $statics[ $name ] );
    // don't worry about checking for existence
    // values of unset variables and array keys always are null
    // that's what you should return
    return $statics[ $name ];
  }
}
Run Code Online (Sandbox Code Playgroud)

关于你的第二个问题,你可以DateClass::statics()在任何地方使用,甚至在DateClass. PHP4 还允许您作为实例方法进行调用DateClass::statics(),即使您不应该这样做。(也可以静态调用实例方法,只要外部作用域中有 $this 即可。这不太好,你绝对不应该这样做;-)

如果您确实希望调用DateClass更加动态,可以使用call_user_func,它只是更详细一些。

<?php
class DateClass {
  function statics( ... ) { ... }
  function anotherStaticFunc() {
    var_dump( DateClass::statics( 'months' ) );
    // using __CLASS__ and call_user_func
    var_dump(
      call_user_func( array( __CLASS__, 'statics' ), 'months' )
    );
  }
  function instanceMethod() {
    var_dump( $this->statics( 'months' ) );
  }
}
Run Code Online (Sandbox Code Playgroud)