php get public properties

ReflectionClass::getProperties

ReflectionClass::getProperties — Возвращает свойства

Описание

Возвращает reflected (отражённые) свойства.

Список параметров

Опциональный фильтр, позволяющий возвращать только желаемые типы свойств. Он настраивается с помощью констант ReflectionProperty, по умолчанию позволяет возвращать свойства всех типов.

Возвращаемые значения

Список изменений

Примеры

Пример #1 Пример фильтрации с помощью ReflectionClass::getProperties()

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

User Contributed Notes 6 notes

Note that inherited properties are returned, but no private properties of parent classes. Depending on the use case, you need to check that, too.

Some may find this useful.

function abc () <
//do something
>
>

function edf () <
//do something
>
>

class AAA extends AA <
//may not have extra properties, but may have extra methods
function ghi () <
//ok
>
>

Looks like you can access public, protected, private variables by casting the object to an array (useful for Unit Testing). However casting to an array still won’t allow you access to protected and private static variables.

In PHP 5.3.0+ use ReflectionProperty::setAccessable(true);

PHP Version: 5.1.6
Array
(
[foo] => public
[*bar] => protected
[Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const

With PHP 5.3 protected or private properties are easy to access with setAccessible(). However, it’s sometimes needed (e.g. Unit Tests) and here is a workaround for getValue():

?>

Note that it wont work if you access the property directly with getProperty().

Источник

Get public properties that aren’t static with PHP Reflection

PHP has a Reflection API adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. I needed to use it to get all the publicly accessible properties for a class that aren’t static, but there doesn’t seem to be a way to get this «out of the box».

This post has my solution, but feel free to let me know a better way of doing it in the comments.

$properties will now contain only the properties that are public and not static. If you are using namespaces, you’ll probably need to prefix ReflectionClass and ReflectionProperty with so they look like ReflectionClass and ReflectionProperty.

Longer answer

The following class «foo» has three public static properties (a, b, c) and three regular public properties (d, e, f). The «reflect» method echoes out all the public properties.

Calling the «reflect» method liek this:

This includes the static properties, and I couldn’t work out any way to exclude them. Again, as noted at the top of this post, please feel free to let me know if there is a way to do it easily when calling the getProperties() method.

In order to get just the public properties that are not static, the only way I could see to do it was to get the IS_STATIC properties and use array_diff() to get only the public ones.

The revised class looks like this:

The output from reflect() now looks like this:

Is there a better way to do this? Please let me know in the comments section.

Источник

get_object_vars

(PHP 4, PHP 5, PHP 7, PHP 8)

get_object_vars — Gets the properties of the given object

Description

Gets the accessible non-static properties of the given object according to scope.

Parameters

An object instance.

Return Values

Returns an associative array of defined object accessible non-static properties for the specified object in scope.

Examples

Example #1 Use of get_object_vars()

The above example will output:

Uninitialized properties are considered inaccessible, and thus will not be included in the array.

See Also

User Contributed Notes 4 notes

You can still cast the object to an array to get all its members and see its visibility. Example:

\n» ;
echo «Using get_object_vars:\n» ;

echo «\n\nUsing array cast:\n» ;

Using get_object_vars:
Array
(
[skin] => 1
)

Using array cast:
Array
(
[skin] => 1
[ * meat] => 2
[ Potatoe roots] => 3
)

As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are ‘\0’ characters, so the general rule to parse keys seems to be:

Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name

I’ve wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:

?>

I’ve created also a bless function that works similar to Perl’s bless, so you can further recast the array converting it in an object of an specific class:

\n» ;
echo «Using get_object_vars:\n» ;

echo «\n\nUsing obj2array func:\n» ;

echo «\n\nSetting all members to 0.\n» ;
$Arr [ ‘skin’ ]= 0 ;
$Arr [ ‘meat’ ]= 0 ;
$Arr [ ‘roots’ ]= 0 ;

You can use an anonymous class to return public variables from inside the class:

$test = new Test();
print_r(get_object_vars($test)); // array(«public» => NULL)
print_r($test->getAllVars()); // array(«protected» => NULL, «public» => NULL, «private» => NULL)
print_r($test->getPublicVars()); // array(«public» => NULL)

It seems like there’s no function that determines all the *static* variables of a class.

I’ve come out with this one as I needed it in a project:

When dealing with a very large quantity of objects, it is worth noting that using `get_object_vars()` may drastically increase memory usage.

If instantiated objects only use predefined properties from a class then PHP can use a single hashtable for the class properties, and small memory-efficient arrays for the object properties:

However, if you call `get_object_vars()` on an object like this, then PHP WILL build a hashtable for the individual object. If you have a large quantity of objects, and you call `get_object_vars()` on all of them, then a hashtable will be built for each object, resulting in a lot more memory usage. This can be seen in this bug report: https://bugs.php.net/bug.php?id=79392

The effects of this can be seen in this example:

printMem ( ‘before get_object_vars’ );

printMem ( ‘get_object_vars using clone’ );

// The memory is used even if you do not modify the object.
>

printMem ( ‘get_object_vars direct access’ );
?>

The output of this is:

start: 405704 (0.41 MB)
before get_object_vars: 6512416 (6.51 MB)
get_object_vars using clone: 6033408 (6.03 MB)
get_object_vars direct access: 13553408 (13.55 MB)

In short, if you are using classes to avoid additional memory usage associated with hashtables (like in associative arrays), be aware that `get_object_vars()` will create a hashtable for any object passed to it.

This appears to be present in all versions of PHP; I’ve tested it on PHP 5, 7, and 8.

Quotes are from Nikic’s blog posts on arrays and hashtable memory usage, and Github gist «Why objects (usually) use less memory than arrays in PHP».

Источник

get_class_vars

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class_vars — Get the default properties of the class

Description

Get the default properties of the given class.

Parameters

Return Values

Examples

Example #1 get_class_vars() example

$my_class = new myclass ();

The above example will output:

Example #2 get_class_vars() and scoping behaviour

public static function expose ()
<
echo format ( get_class_vars ( __CLASS__ ));
>
>

TestCase :: expose ();
echo format ( get_class_vars ( ‘TestCase’ ));
?>

The above example will output:

See Also

User Contributed Notes 15 notes

public static function getFields ()
<
return self :: _getFields ( __CLASS__ );
>

abstract public static function getFields ();

var_dump ( childClass :: getFields ());
?>

Results:
array(4) <
[0]=>
string(2) «id»
[1]=>
string(4) «name»
[2]=>
string(10) «idInParent»
[3]=>
string(12) «nameInParent»
>

All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array. For serialization I recommend:

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.

I needed to get only the class static variables, leaving out instance variables.

If you need get the child protected/private vars ignoring the parent vars, use like this:

$child_class = new childClass ();
?>

If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

class Foo <
const Bar = «error» ;

print_r ( get_class_vars ( «Foo» ));

?>

. but using «Foo::Bar» instead «self::Bar» will work 😉

class someClass <
public function toArray () <
$records = array();

in PHP5 to get all the vars (including private etc.) use:

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.

Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

( get_class_vars ( «Foo» ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).

This is one of the best php functions. Look at what you can do

Now you can do really cool things. If you have a form like

when you submmit the form, you can get the data like

$person = new Person($_POST);

This is my core Object for everthing I do and it works great.

get_class_vars_assoc()
— Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

public static function load () <
print_r ( self :: get_class_vars_assoc ());
>

[ParentClass] => Array
(
[1] => parentVar
[2] => in_parent_and_child
)

[GrandClass] => Array
(
[0] => grandVar
[1] => in_grand_and_parent
[2] => in_grand_and_child
)

Источник

Accessing private properties in PHP

Private properties can only be accessed by the class that defines the property… right? Actually, PHP has a few ways to circumvent this: reflection, closures and array casting.

Reflection: slow, but clean

Closures: an interesting alternative

The idea is to create a getter using a closure, and then bind it to the class you want to access.

While this is pretty cool, it gets even better. You can retrieve the private property by reference. So not only will you be able to retrieve its value, you’ll be able to change it as well. Neat!

Casting to array

As a last option, we’ll abuse PHP’s implementation of casting an object to an array. When you cast an object to an array, all properties get exposed. Let’s see it in action:

As you can see, PHP uses a null character to separate the visibility scope from the property name.

While this is technically undefined behaviour, a test case has been created to ensure it doesn’t get changed. Knowing this, we can create a way to access any property we want.

This is far from ideal however. unserialize is slow, and the resulting object is a new instance. This makes it pretty useless. On top of that, the code needed to achieve this looks really ugly.

One note here: we’re abusing undefined behaviour. There is no guarantee this will continue to work in future PHP versions.

Performance

So, we’ve got a couple of ways to access and even mutate private properties. But what about performance? I’ve put together some benchmarking code to test this. While not 100% accurate, it gives us an indication about the relative performance. The results for 1 million iterations:

This shows us a couple of things:

Conclusion

If you’re concerned about speed, cast your object to an array to read it, and use array_walk to write to it. It’s really fast! However, if you’re writing production code, consider if you really want to do this. Properties are private for a reason! If you have a valid use case, go for reflection. Your code will be more readable and thus easier to maintain. Plus, its behaviour is well-defined and documented. The performance gain isn’t worth sacrificing this for.

Читайте также

Depending on your needs, you should consider using filter_var() with the FILTER_VALIDATE_BOOLEAN flag.filter_var( ‘true’, FILTER_VALIDATE_BOOLEAN); // true filter_var( 1, FILTER_VALIDATE_BOOLEAN);…

Why does this program panic?var m map[string]float64 m[«pi»] = 3.1416panic: assignment to entry in nil mapAnswerYou have to initialize the…

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *