PHP自带有get_object_vars函数,非常强大,可以将一个对象里的可见属性(Public)转换为数组。这个函数对于一些“历史遗留”的非面向对象程序的适应非常好。
但有一点非常苦恼的是,如果在类里面的代码调用这个get_object_vars,会将所有这个类里面所有可见的属性(包括了public、protected、private三种)都转换到数组,这是我不希望的。究其原因,应该是在类里面的可见度高了。如何解决这个问题?
今天搜索了一下,发现一个鬼佬写了一个强大而又精焊的方法内置在类里面,不由感慨“神奇的PHP”。非常好用,特此分享。
原文:http://www.vancelucas.com/blog/get-only-public-class-properties-for-current-class-in-php/
PHP provides two built-in functions to retrieve properties of a given class –get_object_vars and get_class_vars. Both these functions behave the same exact way, one taking an object as a variable and the other taking a string class name. The tricky thing about the two functions is that they behave differently depending on the call scope, returning all of the class variables available within the called scope. So if you call either function within the current class you need properties from, all properties are returned – public, protected, and private – because the current scope has access to them all. This makes seemingly simple things like returning all the public properties within the current class a bit of a pain if you want to keep the code inside the class itself.
The obvious solution is to use the functions from a different call scope, which means either moving the call outside the class to the implementation code (yuck), or creating a new function outside the class for it. A lot of suggestions in the PHP manual say to create a new function below the class definition and call it within the class (kind of a proxy function as a workaround), but that seems tacky. Luckily, PHP also provides another way to get a new call scope: anonymous functions (and closures as of PHP 5.3).
1 2 3 4 5 6 7 8 9 10 11 12 |
class BobUser
{
public $name = 'bob';
public $publicFlag = true;
protected $internalFlag = true;
public function getFields()
{
$getFields = create_function('$obj', 'return get_object_vars($obj);');
return $getFields($this); // Returns only 'name' and 'publicFlag'
}
}
|
We can also do this the PHP 5.3 way with a much nicer-looking closure:
1 2 3 4 5 6 7 8 9 |
class BobUser
{
// ...
public function getFields()
{
$getFields = function($obj) { return get_object_vars($obj); };
return $getFields($this);
}
}
|
Place your comment