drl37530 2013-03-31 23:51
浏览 12

php - 如何将全局值分配给静态类

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 ;                    
      }
  }
  • 写回答

1条回答 默认 最新

  • dqlhsm9820 2013-04-01 02:44
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器