PHP Readonly Properties?

前端 未结 6 1215
闹比i
闹比i 2020-12-05 06:12

In using PHP\'s DOM classes (DOMNode, DOMEElement, etc) I have noticed that they possess truly readonly properties. For example, I can read the $nodeName property of a DOMNo

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 06:36

    For those looking for a way of exposing your private/protected properties for serialization, if you choose to use a getter method to make them readonly, here is a way of doing this (@Matt: for json as an example):

    interface json_serialize {
        public function json_encode( $asJson = true );
        public function json_decode( $value );
    }
    
    class test implements json_serialize {
        public $obj = null;
        protected $num = 123;
        protected $string = 'string';
        protected $vars = array( 'array', 'array' );
        // getter
        public function __get( $name ) {
            return( $this->$name );
        }
        // json_decode
        public function json_encode( $asJson = true ) {
            $result = array();
            foreach( $this as $key => $value )
                if( is_object( $value ) ) {
                    if( $value instanceof json_serialize )
                        $result[$key] = $value->json_encode( false );
                    else
                        trigger_error( 'Object not encoded: ' . get_class( $this ).'::'.$key, E_USER_WARNING );
                } else
                    $result[$key] = $value;
            return( $asJson ? json_encode( $result ) : $result );
        }
        // json_encode
        public function json_decode( $value ) {
            $json = json_decode( $value, true );
            foreach( $json as $key => $value ) {
                // recursively loop through each variable reset them
            }
        }
    }
    $test = new test();
    $test->obj = new test();
    echo $test->string;
    echo $test->json_encode();
    

提交回复
热议问题