简体   繁体   中英

php - how to assign global value to a static class

What is the best way to assign a global value to a static property (from outside of the class)

( I do not want to use constants (ie define( ... ) ).

(since I am using a static class there is no constructor, so I cannot inject the value as an argument)


APPROACH A ... WONT WORK ... my preferred approach, but it does not work

$my_global = "aaa" ;

class my_class
  { public static $my_prop = $GLOBALS[ 'my_global' ] ; // XXX         
  }

APPROACH B ... WORKS, but feels wrong ... I could use an explicit setter, I know, but then I would have a bunch of one-purpose setters.

$my_global = "aaa" ;

my_class::$my_prop = $my_global ; 

class my_class
  { public static $my_prop ;

  }

APPROACH C ... WONT WORK ... using generic setter to assign value to specific property. I would like this approach ok.

$my_global = "aaa" ;

my_class::my_setter( "my_prop" , $my_global ) ;  

class my_class
  { private static $my_prop ;

    public static function my_setter( $prop_name , $value )
      { self::$prop_name   = $value ; // XXX
        self[ $prop_name ] = $value ; // XXX
      }
  }

APPROACH D ... WORKS ... using generic setter to assign value in an 'anonymous' registry. I do not like this approach, because I do not know what is in the registry.

$my_global = "aaa" ;

my_class::my_setter( "my_prop" , $my_global ) ; 

class my_class
  { private static $my_registry = array() ;

    public static function my_setter( $prop_name , $value )
      { self::$my_registry[ $prop_name ] = $value ;                    
      }
  }

The straight forward solution is

class MyClass
{
    public static $property;
}

MyClass::$property = 'aaa';

CAVEAT : You should reconsider your choice. Static classes are not a good idea (if fact, they are singletons), since they have negative impact on testability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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