如何将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 ;
}
使用get_called_class
which 将为您提供静态方法的类的名称
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 $ ---^
}
您可以通过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'];
}
尝试这个
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);
}
}
使用 $this 变量传递 self