PHP/Class/ get — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:00, 26 мая 2010
Enforcing property access using magic accessor methods
<?
class Person {
protected $__data = array("person", "email");
public function __get($property) {
if (isset($this->__data[$property])) {
return $this->__data[$property];
} else {
return false;
}
}
public function __set($property, $value) {
if (isset($this->__data[$property])) {
return $this->__data[$property] = $value;
} else {
return false;
}
}
}
?>
__get( ) specifies what to do if an unknown property is read from within your script
<?
class Dog {
public $Name;
public $DogTag;
public function __get($var) {
print "Attempted to retrieve $var and failed...\n";
}
}
$poppy = new Dog;
print $poppy->Age;
?>
Intercepting Property Access with __get() and __set() (PHP 5 Only)
<?php
class TimeThing {
function __get( $arg ) {
if ( $arg == "time" ) {
return getdate();
}
}
function __set( $arg, $val ) {
if ( $arg == "time" ) {
trigger_error( "cannot set property $arg" );
return false;
}
}
}
$cal = new TimeThing();
print $cal->time["mday"]."/";
print $cal->time["mon"]."/";
print $cal->time["year"];
?>