« | »

PHP Get and Set properties

By Lennard | April 11, 2006


Warning: preg_match() [function.preg-match]: Compilation failed: unrecognized character after (?< at offset 3 in /home/bakkerl/domains/lannerd.nl/public_html/wordpress/wp-content/plugins/codesnippet/lib/geshi.php on line 2132

Warning: preg_match() [function.preg-match]: Compilation failed: unrecognized character after (?< at offset 3 in /home/bakkerl/domains/lannerd.nl/public_html/wordpress/wp-content/plugins/codesnippet/lib/geshi.php on line 2132

I stole this piece of code. But placed it here so i find it back again.

  1. <?php
  2. /*
  3. * Class BaseClass
  4. *
  5. *
  6. *
  7. *
  8. * $objTest = new BaseClass();
  9. * print $objTest->data . "n";
  10. *
  11. * $objTest->data = "bar"; //Works.
  12. * print $objTest->data;
  13. *
  14. * $objTest->id = 5; //Error: Property is read-only.
  15. *
  16. */
  17. class BaseClass
  18. {
  19.  
  20. // EXAMPLE PROPERTIES
  21. private $properties = array(
  22.   "id"       => array("value" => 4,
  23.   "type" => "int",
  24.   "readonly" => true),
  25.   "datetime" => array("value" => "Tue 02/21/2006 20:49:23",
  26.   "type" => "string",
  27.   "readonly" => true),
  28.   "data"     => array("value" => "foo",
  29.   "type" => "string",
  30.   "readonly" => false)
  31. );
  32. // END EXAMPLE PROPERTIES
  33.  
  34. /*
  35. *
  36. */
  37. private function __get($strProperty)
  38. {
  39.   //Get a property:
  40.   if (isset($this->properties[$strProperty]))
  41.     return $this->properties[$strProperty]["value"];
  42.   else
  43.   {
  44.     throw new Exception("Property not defined");
  45.     return false;
  46.   }
  47. }
  48.  
  49. /*
  50. *
  51. */
  52. private function __set($strProperty, $varValue)
  53. {
  54.   //Set a property to a value:
  55.   if (isset($this->properties[$strProperty]))
  56.   {
  57.     //Check if property is read-only:
  58.     if ($this->properties[$strProperty]["readonly"])
  59.     {
  60.       throw new Exception("Property is read-only");
  61.       return false;
  62.     }
  63.     else
  64.     {
  65.       $this->properties[$strProperty]["value"] = $varValue;
  66.       return true;
  67.     }
  68.   }
  69.   else
  70.   {
  71.     throw new Exception("Property not defined");
  72.     return false;
  73.   }
  74. }
  75.  
  76. /*
  77. *
  78. */
  79. private function __isset($strProperty)
  80. {
  81.   //Determine if property is set:
  82.   return isset($this->properties[$strProperty]);
  83. }
  84.  
  85. /*
  86. *
  87. */
  88. private function __unset($strProperty)
  89. {
  90.   //Unset (remove) a property:
  91.   unset($this->properties[$strProperty]);
  92. }
  93.  
  94. }
  95. ?>

Topics: php | No Comments »

Comments