Advertisement
Rofihimam

Untitled

Feb 19th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.61 KB | None | 0 0
  1. <?php
  2.     /**
  3.      *
  4.      */
  5.     class PropertyTest
  6.     {
  7.         // Location for overload data
  8.         private $data = array();
  9.  
  10.         // Overloading not used on declared properties
  11.         public $declared = 1;
  12.  
  13.         // Overloading onnly used on this when accessed outside the class
  14.         private $hidden = 2;
  15.  
  16.         public function __set($name, $value)
  17.         {
  18.             echo "Seeting '$name' to '$value'\n";
  19.             $this->data[$name] = $value;
  20.         }
  21.  
  22.         public function __get($name)
  23.         {
  24.             echo "Getting '$name'\n";
  25.             if (array_key_exists($name, $this->data)) {
  26.                 return $this->data[$name];
  27.             }
  28.  
  29.             $trace = debug_backtrace();
  30.             trigger_error(
  31.                 'Undefined property via __get();'.$name.
  32.                 'in'.$trace[0]['file'].
  33.                 'on line'.$trace[0]['line'],
  34.                 E_USER_NOTICE
  35.             );
  36.             return null;
  37.         }
  38.  
  39.         // As of PHP 5.1.0
  40.         public function __isset($name)
  41.         {
  42.             echo "Is '$name' set?\n";
  43.             return isset($this->data[$name]);
  44.         }
  45.  
  46.         // As of PHP 5.1.0
  47.         public function __unset($name)
  48.         {
  49.             echo "Unsetting '$name'\n";
  50.             unset($this->data[$name]);
  51.         }
  52.  
  53.         // Not a magic method, just here for example
  54.         public function getHidden()
  55.         {
  56.             return $this->hidden;
  57.         }
  58.     }
  59.  
  60.     echo "<pre>\n";
  61.  
  62.     $obj = new PropertyTest;
  63.  
  64.     $obj->a = 1;
  65.     echo $obj->a."\n\n";
  66.  
  67.     var_dump(isset($obj->a));
  68.     unset($obj->a);
  69.     var_dump(isset($obj->a));
  70.     echo "\n";
  71.  
  72.     echo $obj->declared."\n\n";
  73.  
  74.     echo "Let's experiment with the private property named 'hidden':\n";
  75.     echo "Privates are visible inside the class, so __get() not used...\n";
  76.     echo $obj->getHidden()."\n";
  77.     echo "Privates not visible outside the class, so __get() is used...\n";
  78.     echo $obj->hidden."\n";
  79. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement