Skip to content

Instantly share code, notes, and snippets.

@anon5r
Created October 9, 2012 06:02
Show Gist options
  • Save anon5r/3856906 to your computer and use it in GitHub Desktop.
Save anon5r/3856906 to your computer and use it in GitHub Desktop.
コンストラクタの引数に渡された連想配列のキーをプロパティ名、値をプロパティの値として保持するオブジェクトを生成できるようにする
<?php
class ReadonlyProperties {
private $__props = array();
public function __construct( array $params ) {
$this->__props = $params;
}
public function __get( $_name ) {
if ( $_name == '__props' ) {
$trace = debug_backtrace();
trigger_error( 'Undefined property : ' . $_name . ' in ' . $trace[ 0 ][ 'file' ] . ' on line ' . $trace[ 0 ][ 'line' ], E_USER_NOTICE );
}
if ( isset( $this->__props[ $_name ] ) == false ) {
$trace = debug_backtrace();
trigger_error( 'Undefined property : ' . $_name . '. in ' . $trace[ 0 ][ 'file' ] . ' on line ' . $trace[ 0 ][ 'line' ], E_USER_WARNING );
}
return $this->__props[ $_name ];
}
public function __set( $_name, $value ) {
if ( isset( $this->__props[ $_name ] ) == true ) {
$trace = debug_backtrace();
trigger_error( 'Unable to set property : ' . $_name . '. This property is read only. in ' . $trace[ 0 ][ 'file' ] . ' on line ' . $trace[ 0 ][ 'line' ], E_USER_ERROR );
}
$trace = debug_backtrace();
trigger_error( 'Undefined property : ' . $_name . '. Can not set value. in ' . $trace[ 0 ][ 'file' ] . ' on line ' . $trace[ 0 ][ 'line' ], E_USER_WARNING );
}
public function __isset( $_name ) {
if ( $_name == '__props' ) return false;
return isset( $this->__props[ $_name ] );
}
public function __unset( $_name ) {
if ( isset( $this->__props[ $_name ] ) == true ) {
$trace = debug_backtrace();
trigger_error( 'Unable to unset property : ' . $_name . '. This property is read only. in ' . $trace[ 0 ][ 'file' ] . ' on line ' . $trace[ 0 ][ 'line' ], E_USER_ERROR );
}
$trace = debug_backtrace();
trigger_error( 'Undefined property : ' . $_name . '. Can not set value. in ' . $trace[ 0 ][ 'file' ] . ' on line ' . $trace[ 0 ][ 'line' ], E_USER_WARNING );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment