getter __get magico per le proprietà statiche in PHP
-
16-09-2019 - |
Domanda
public static function __get($value)
non funziona, e anche se lo facesse, si dà il caso che ho già bisogno della magia __get getter per proprietà di istanza della stessa classe.
Questa probabilmente è una domanda sì o no, quindi, è possibile?
Soluzione
No, non è possibile.
Gli sovraccarico funziona solo in contesto dell'oggetto. Questi metodi di magia non sarà attivato in statica contesto. Pertanto questi metodi possono Non essere dichiarato statico.
In PHP 5.3, __callStatic
è stato aggiunto; ma non c'è né __getStatic
__setStatic
ancora; anche se l'idea di avere / loro codifica viene spesso indietro sulla interni php @ mailling-list.
C'è anche un href="http://wiki.php.net/rfc/static-classes" di Commenti: classi statiche per PHP
Ma, ancora, non implementato (ancora?)
Altri suggerimenti
Forse qualcuno ancora bisogno di questo:
static public function __callStatic($method, $args) {
if (preg_match('/^([gs]et)([A-Z])(.*)$/', $method, $match)) {
$reflector = new \ReflectionClass(__CLASS__);
$property = strtolower($match[2]). $match[3];
if ($reflector->hasProperty($property)) {
$property = $reflector->getProperty($property);
switch($match[1]) {
case 'get': return $property->getValue();
case 'set': return $property->setValue($args[0]);
}
} else throw new InvalidArgumentException("Property {$property} doesn't exist");
}
}
Molto bello mbrzuchalski. Ma sembra funzionare solo su variabili pubbliche. Basta cambiare il vostro interruttore a questo per permettere di accedere quelle private / protette:
switch($match[1]) {
case 'get': return self::${$property->name};
case 'set': return self::${$property->name} = $args[0];
}
E si sarebbe probabilmente desidera modificare l'istruzione if
per limitare le variabili che sono accessibili, altrimenti verrebbe vanificato l'obiettivo di avere loro di essere private o protette.
if ($reflector->hasProperty($property) && in_array($property, array("allowedBVariable1", "allowedVariable2"))) {...)
Così, per esempio, ho una classe progettato per estrarre i vari dati per me da un server remoto utilizzando un modulo SSH pera, e lo voglio fare alcune ipotesi circa la directory di destinazione in base a quale server è stato chiesto di guardare a. Una versione ottimizzato del metodo di mbrzuchalski è perfetta per questo.
static public function __callStatic($method, $args) {
if (preg_match('/^([gs]et)([A-Z])(.*)$/', $method, $match)) {
$reflector = new \ReflectionClass(__CLASS__);
$property = strtolower($match[2]). $match[3];
if ($reflector->hasProperty($property)) {
if ($property == "server") {
$property = $reflector->getProperty($property);
switch($match[1]) {
case 'set':
self::${$property->name} = $args[0];
if ($args[0] == "server1") self::$targetDir = "/mnt/source/";
elseif($args[0] == "server2") self::$targetDir = "/source/";
else self::$targetDir = "/";
case 'get': return self::${$property->name};
}
} else throw new InvalidArgumentException("Property {$property} is not publicly accessible.");
} else throw new InvalidArgumentException("Property {$property} doesn't exist.");
}
}
provare questo:
class nameClass{
private static $_sData = [];
private static $object = null;
private $_oData = [];
public function __construct($data=[]){
$this->_oData = $data;
}
public static function setData($data=[]){
self::$_sData = $data;
}
public static function Data(){
if( empty( self::$object ) ){
self::$object = new self( self::$_sData );
}
return self::$object;
}
public function __get($key) {
if( isset($this->_oData[$key] ){
return $this->_oData[$key];
}
}
public function __set($key, $value) {
$this->_oData[$key] = $value;
}
}
nameClass::setData([
'data1'=>'val1',
'data2'=>'val2',
'data3'=>'val3',
'datan'=>'valn'
]);
nameClass::Data()->data1 = 'newValue';
echo(nameClass::Data()->data1);
echo(nameClass::Data()->data2);
Inoltre, è possibile ottenere le proprietà statiche di accedervi come proprietà dei membri, utilizzando __get ():
class ClassName {
private static $data = 'smth';
function __get($field){
if (isset($this->$field)){
return $this->$field;
}
if(isset(self::$$field)){
return self::$$field; // here you can get value of static property
}
return NULL;
}
}
$obj = new ClassName();
echo $obj->data; // "smth"
La combinazione __callStatic
e call_user_func
o call_user_func_array
può dare l'accesso alle proprietà statiche in classe PHP
Esempio:
class myClass {
private static $instance;
public function __construct() {
if (!self::$instance) {
self::$instance = $this;
}
return self::$instance;
}
public static function __callStatic($method, $args) {
if (!self::$instance) {
new self();
}
if (substr($method, 0, 1) == '$') {
$method = substr($method, 1);
}
if ($method == 'instance') {
return self::$instance;
} elseif ($method == 'not_exist') {
echo "Not implemented\n";
}
}
public function myFunc() {
echo "myFunc()\n";
}
}
// Getting $instance
$instance = call_user_func('myClass::$instance');
$instance->myFunc();
// Access to undeclared
call_user_func('myClass::$not_exist');