note 109682 deleted from language.oop5.overloading by danbrown
| From: | danbrown@php.net | Date: | Fri, 10 Aug 2012 16:06:58 +0000 |
| Subject: | note 109682 deleted from language.oop5.overloading by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189991@lists.php.net to get a copy of this message | ||
Note Submitter: josema dot enzo at gmail dot com
----
<?php
///////////////////////////////////////////////////////////////////////////////////////
//
// Base class of encapsulation methods for subclasses (SPSERVER)
//
// 2012/VIII/8
//
///////////////////////////////////////////////////////////////////////////////////////
namespace spserver;
class Encapsulation
{
/////////////////
// VARIABLES //
/////////////////
/**
* If the variable can be getted you need to add the string of the var in this array
* @var array
*/
private $gets = array();
/**
* If the variable can be setted you need to add the string of the var in this array
* @var array
*/
private $sets = array();
///////////////
// METHODS //
///////////////
public function __get($name)
{
if (isset($this->{$name}) && isset($this->gets[$name]))
return (gettype($this->gets[$name]) == 'string' && method_exists($this,
$this->gets[$name])) ?
$this->{$this->gets[$name]}()
:
$this->{$name};
else
trigger_error("You can't get the property " . get_class($this) .
"::\$$name", E_USER_NOTICE);
}
public function __set($name,$value)
{
if (isset($this->{$name}) && isset($this->sets[$name]))
(gettype($this->sets[$name]) == 'string' && method_exists($this,
$this->sets[$name])) ?
$this->{$this->sets[$name]}($value)
:
$this->{$name} = $value;
else
trigger_error("You can't set the property " . get_class($this) .
"::\$$name", E_USER_NOTICE);
}
public function addGet($name, $callBackFunction=false)
{
$this->gets[$name] = $callBackFunction;
}
public function addSet($name, $callBackFunction=false)
{
$this->sets[$name] = $callBackFunction;
}
public function __isset($name)
{
return isset($this->{$name});
}
}
?>
<pre>
<?php
class PropertyTest extends Encapsulation
{
protected $a = 10;
protected $b = 20;
protected $c = 30;
public function __construct()
{
$this->addGet('a');
$this->addSet('a','setA');
$this->addGet('b','getB');
$this->addSet('b');
$this->addGet('c');
//$this->addSet('c');
}
protected function getB()
{
return $this->b+1;
}
protected function setA($value)
{
$this->a = ($value+1);
}
}
$obj = new PropertyTest;
var_dump($obj->a); //int 10
var_dump($obj->b); //int 21
var_dump($obj->c); //int 30
$obj->a = 1000;
$obj->b = 2000;
$obj->c = 3000; //Error User Notice
var_dump($obj->a); //int 1001
var_dump($obj->b); //int 2001
var_dump($obj->c); //int 30
?>
</pre>