Add attribute to an object in PHP

前端 未结 3 1279
终归单人心
终归单人心 2021-01-03 17:49

How do you add an attribute to an Object in PHP?

3条回答
  •  一向
    一向 (楼主)
    2021-01-03 18:18

    this is a static class but, the same principle would go for an intantiated one as well. this lets you store and retrieve whatever you want from this class. and throws an error if you try to get something that is not set.

    class Settings{
        protected static $_values = array();
    
    public static function write( $varName, $val ){ 
        self::$_values[ $varName ] = $val; 
    }
    public static function read( $varName ){ 
    
        if( !isset( self::$_values[ $varName ] )){
            throw new Exception( $varName . ' does not exist in Settings' );
        }
    
        return self::$_values[ $varName ]; 
    }
    }
    

提交回复
热议问题