Hi. all ,
I got a article from php 5.0 manual's comments. It's useful, offer readonly
properties for classes.
(look at the end of this message for the article )
find out function __construct(), I want to modify $this->id in it , then I
got a "readonly" Exception (defined in "__set" function).
Distinctly, a read-only property could not be change via "$obj->attribute =
'' " ,
but is could be change via $this->id='', inside of class , isn't it ?
How to modify __set function ?
thanks for any advises.
regards!
ked
the article is here:
----------------------------------------------------------------------------
------------------------
Eric Lafkoff (22-Feb-2006 02:56)
If you're wondering how to create read-only properties for your class, the
__get() and __set() functions are what you're looking for. You just have to
create the framework and code to implement this functionality.
Here's a quick example I've written. This code doesn't take advantage of the
"type" attribute in the properties array, but is there for ideas.
<?php
class Test
{
private $p_arrPublicProperties = array(
"id" => array("value" => 4,"type" => "int","readonly" => true),
"datetime" => array("value" => "Tue 02/21/2006 20:49:23","type" =>
"string", "readonly" => true),
"data" => array("value" => "foo", "type" => "string", "readonly" =>
false)
);
//ked add!!!!!!!
public function __construct()
{
$this->id = 100; //----------------------------will get exception
!!
}
private function __get($strProperty) {
//Get a property:
if (isset($this->p_arrPublicProperties[$strProperty])) {
return $this->p_arrPublicProperties[$strProperty]["value"];
} else {
throw new Exception("Property not defined");
return false;
}
}
private function __set($strProperty, $varValue) {
//Set a property to a value:
if (isset($this->p_arrPublicProperties[$strProperty])) {
//Check if property is read-only:
if ($this->p_arrPublicProperties[$strProperty]["readonly"]) {
throw new Exception("Property is read-only");
///////////////////////////////////---------------note here
return false;
} else {
$this->p_arrPublicProperties[$strProperty]["value"] = $varValue;
return true;
}
} else {
throw new Exception("Property not defined");
return false;
}
}
private function __isset($strProperty) {
//Determine if property is set:
return isset($this->p_arrPublicProperties[$strProperty]);
}
private function __unset($strProperty) {
//Unset (remove) a property:
unset($this->p_arrPublicProperties[$strProperty]);
}
}
$objTest = new Test();
print $objTest->data . "\n";
$objTest->data = "bar"; //Works.
print $objTest->data;
$objTest->id = 5; //Error: Property is read-only.
?>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php