1

如何将self传递给全局函数

class A
{
  public static $A_var = "hello" ;

  private static  function A_function()
  {
    some_global_function( self ) ;
  }
}

然后接收它:

function some_global_function( $argo_self ) 
{
  echo $argo_self::A_var ;
} 
4

4 回答 4

3

使用get_called_classwhich 将为您提供静态方法的类的名称

class A
{ 
    public static $A_var = "hello" ;

    private static function A_function()
    { 
        some_global_function( get_called_class() ) ;
    }
}

您应该注意,要访问$A_var您需要执行此操作,此时您正在尝试访问一个名为A_var

function some_global_function( $argo_self ) 
{
    echo $argo_self::$A_var ;
    // note the $ ---^ 
} 
于 2013-03-24T13:33:19.700 回答
1

您可以通过ReflectionClass::getStaticProperties()获取所有可用的静态字段:

private static  function A_function()
{
  // pass class name
  some_global_function( 'A' ) ;
}

function some_global_function( $className ) 
{
  $reflClass = new ReflectionClass($className);
  $staticProps = $reflClass->getStaticProperties();

  echo $staticProps['A_var'];
}

现场演示:http ://codepad.org/6ZZjNtXC

于 2013-03-24T13:33:17.207 回答
0

尝试这个

class ExampleClass {

    // Create loaded variable as to only init once
    static $loaded = false;

    // Create static variable to hold self
    static $self;

    // Create initialization function to assign self to self::$self
    public static function init() {

        // Assign the current class to self::$self
        self::$self = get_called_class();

        // Set self::$loaded to true to prevent double execution
        self::$loaded = true;
    }

    public static function someFunction() {

        // Check to see if static class has been initialized
        if(self::$loaded == false) {

            // Initialize static class
            self::init();
        }

        // Pass this static class to the destination function
        some_global_function(self::$self);
    }
}
于 2014-02-23T10:41:20.473 回答
-1

使用 $this 变量传递 self

于 2013-03-24T13:30:57.617 回答