php get class properties

ReflectionClass::getProperties

ReflectionClass::getProperties — Gets properties

Description

Retrieves reflected properties.

Parameters

The optional filter, for filtering desired property types. It’s configured using the ReflectionProperty constants, and defaults to all property types.

Return Values

Changelog

Examples

Example #1 ReflectionClass::getProperties() filtering example

This example demonstrates usage of the optional filter parameter, where it essentially skips private properties.

The above example will output something similar to:

See Also

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_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
)

Источник

get_class

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

get_class — Returns the name of the class of an object

Description

Parameters

The tested object. This parameter may be omitted when inside a class.

Note: Explicitly passing null as the object is no longer allowed as of PHP 7.2.0. The parameter is still optional and calling get_class() without a parameter from inside a class will work, but passing null now emits an E_WARNING notice.

Return Values

Returns the name of the class of which object is an instance. Returns false if object is not an object.

If object is omitted when inside a class, the name of that class is returned.

If the object is an instance of a class which exists in a namespace, the qualified namespaced name of that class is returned.

Errors/Exceptions

If get_class() is called with anything other than an object, an E_WARNING level error is raised.

Changelog

Examples

Example #1 Using get_class()

// create an object
$bar = new foo ();

The above example will output:

Example #2 Using get_class() in superclass

class foo extends bar <
>

The above example will output:

Example #3 Using get_class() with namespaced classes

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

The above example will output:

See Also

User Contributed Notes 36 notes

::class
fully qualified class name, instead of get_class

namespace my \ library \ mvc ;

print Dispatcher ::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher ;

(For reference, here’s the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

class Foo
<
public function __construct ()
<
echo «Foo» ;
>
>

People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here’s a good example that should fix that for ever:

class Bar extends Foo <

$foo = new Foo ();
$bar = new Bar ();
$quux = new Quux ();

—doMethod—
Foo::doMethod
Foo::doMethod
Quux::doMethod

—doGetClassThis—
Foo::doThat
Bar::doThat
Quux::doThat

—doGetClass—
Foo::doThat
Foo::doThat
Quux::doThat

In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not ‘know’ the name of the calling subclass’, so I use a backtrace to determine it. I don’t like hacks like this, but as long as PHP doesn’t have an alternative, this is what has to be done:

Simplest way how to gets Class without namespace

namespace a \ b \ c \ d \ e \ f ;

echo new Foo (); // prints Foo
?>

Need a quick way to parse the name of a class when it’s namespaced? Try this:

/**
* Obtains an object class name without namespaces
*/
function get_real_class($obj) <
$classname = get_class($obj);

With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

namespace Foo \ Bar ;

class Snafu extends Baz
<
>

__CLASS__ Foo\Bar\Baz Baz
get_called_class Foo\Bar\Snafu Snafu

The code in my previous comment was not completely correct. I think this one is.

/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() <
$implementing_class = static::$__CLASS__;
$original_class = __CLASS__;

There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

private function __construct () <
// Singleton
>
>

class MySubclass extends MySuperclass <
>

Although you can call a class’s static methods from an instance of the class as though they were object instance methods, it’s nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

If you want the path to an file if you have i file structure like this

and foo() in foo.php extends controller() in controller.php like this

namespace system \ modules \ foo ;

class foo extends \ system \ libs \ controller <
public function __construct () <
parent :: __construct ();
>
>
?>

and you want to know the path to foo.php in controller() this may help you

namespace system \ libs ;

well, if you call get_class() on an aliased class, you will get the original class name

Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it’s not available. Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

default: throw new Exception ( «Unknown backtrace method type» );
>
>
>

class B extends Singleton <
>

class C extends Singleton <
>

Method for pulling the name of a class with namespaces pre-stripped.

namespace testme \ here ;

public function test ()
<
return get_class_name ( get_class ());
>
>

As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the «self» keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the «self» keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

However, assuming compile-time binding (where the keyword «self» refers to the class in which the method is defined), which is how php works, the output would be:

The oddity here is that «$this» is bound at runtime to the actual class of the object (obviously) but «self» is bound at compile-time, which seems counter-intuitive to me. «self» is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which «self» ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to «self» being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the «self» keyword for static methods:

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

I realise that some people might respond «why don’t use just just the class name with ‘ Class’ appended instead of the classDisplayName() method», which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.

Источник

get_object_vars

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

get_object_vars — Возвращает свойства указанного объекта

Описание

Возвращает видимые нестатические свойства указанного объекта object в соответствии с областью видимости.

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

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

Примеры

Пример #1 Пример использования get_object_vars()

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

Неинициализированные свойства считаются недоступными и поэтому не включаются в массив.

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

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».

Источник

How to get all private var names from a class in PHP? [duplicate]

get_class_vars gets all public vars, but I want to access private ones.

I am doing it from a parent class, trying to get the child class vars.

Is there another method to do this?

3 Answers 3

I would suggest using PHP’s ReflectionClass. In particular the getProperties() call.

Here is the PHP documentation:

As sample would be:

Also note that you can change the filter on getProperties methods or omit it altogether (here I have shown the filter for private only).

php get class properties. Смотреть фото php get class properties. Смотреть картинку php get class properties. Картинка про php get class properties. Фото php get class properties

Use ReflectionClass to get them in an array. Then you can do whatever you want. An example code to print their names on the screen.

If you need, declare it as protected, this way you will be able to directly access properties in parent and extending classes.

Other way is to define protected/public getter/setter function in class introducing this property.

Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

Linked

Related

Hot Network Questions

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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

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