Come ottenere le proprietà pubbliche di una classe?
-
19-09-2019 - |
Domanda
Non posso usare semplicemente get_class_vars()
perché ne ho bisogno di lavorare con la versione di PHP precedenti alla 5.0.3 (vedi http://pl.php.net/get_class_vars Changelog)
In alternativa:? Come posso verificare se la proprietà è pubblica
Soluzione
Questo è possibile utilizzando riflessione.
<?php
class Foo {
public $alpha = 1;
protected $beta = 2;
private $gamma = 3;
}
$ref = new ReflectionClass('Foo');
print_r($ref->getProperties(ReflectionProperty::IS_PUBLIC));
il risultato è il seguente:
Array
(
[0] => ReflectionProperty Object
(
[name] => alpha
[class] => Foo
)
)
Altri suggerimenti
In alternativa si può fare questo:
$getPublicProperties = create_function('$object', 'return get_object_vars($object);');
var_dump($getPublicProperties($this));
È possibile effettuare la classe implementi l'interfaccia IteratorAggregate
class Test implements IteratorAggregate
{
public PublicVar01 = "Value01";
public PublicVar02 = "Value02";
protected ProtectedVar;
private PrivateVar;
public function getIterator()
{
return new ArrayIterator($this);
}
}
$t = new Test()
foreach ($t as $key => $value)
{
echo $key." = ".$value."<br>";
}
Questa uscita volontà:
PublicVar01 = Value01
PublicVar02 = Value02
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow