php get instance of object

I want to get an instance of an existing object. How do I do this without having to pass the object as a parameter? This is what I’m doing now:

The output of var_dump is:

I suppose I could have each object as a property of a parent object, but is are there any other suggestions?

php get instance of object. Смотреть фото php get instance of object. Смотреть картинку php get instance of object. Картинка про php get instance of object. Фото php get instance of object

2 Answers 2

Pulling objects by calling static methods (like in singleton) is a bad practice (or even an anti-pattern). Singleton and static classes feel natural for newcomers because they work the same way we learned in the procedural paradigm, but you should avoid them (only use static classes when they have no state)

You should totally pass the object as a parameter, to avoid introducing implicit dependencies, and do good OOP.

Read about Dependency Injection.

If object creation becomes complex or annoying, you can always use a Dependency Injection Container

php get instance of object. Смотреть фото php get instance of object. Смотреть картинку php get instance of object. Картинка про php get instance of object. Фото php get instance of object

You should use sigleton pattern:

php get instance of object. Смотреть фото php get instance of object. Смотреть картинку php get instance of object. Картинка про php get instance of object. Фото php get instance of object

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

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

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.

Источник

Get Instance ID of an Object in PHP

I’ve learn a while ago on StackOverflow that we can get the «instance ID» of any resource, for instance:

I need something similar but applied to classes:

The above works but I was hoping for a faster solution or, at least, one that didn’t involve output buffers. Please note that this won’t necessarily be used within the constructor or even inside the class itself!

spl_object_hash() is not what I’m looking for because the two objects produce identical hashes

The question previously contained an incorrect example of spl_object_hash output; ensuring that both objects exist at the same time produces hashes which are subtly different:

Casting to int like resources doesn’t seem to work for objects:

Notice: Object of class foo could not be converted to int.

Is there a quick way to grab the same output without using object properties?

10 Answers 10

spl_object_hash() could help you out here. It

returns a unique identifier for the object

which is always the same for a given instance.

EDIT after OP comment:

You could implement such a behavior using a static class property, e.g:

But actually this has nothing to with your original question.

Well, yes, with an extension.

Note that the handles used for objects that were, in the meantime, destroyed, can be reused.

testext.h

testext.c

config.m4

Test script

Output

Note that you’ll need PHP 5 >= 5.2.0 for that to work.

php get instance of object. Смотреть фото php get instance of object. Смотреть картинку php get instance of object. Картинка про php get instance of object. Фото php get instance of object

Alix, your solution in the question was exactly what I needed, but actually breaks when there’s an object in an object, returns the last # in the var_dump. I fixed this, made the regex faster, and put it in a nice little function.

As long as you implement the base class all the classes you’re going to need this from, you can do something like this:

The output would be:

As of PHP 7.2 you can use spl_object_id

php get instance of object. Смотреть фото php get instance of object. Смотреть картинку php get instance of object. Картинка про php get instance of object. Фото php get instance of object

What you’re trying to do, is actually Aspect-Oriented Programming (AOP).

There are at least a couple of frameworks available for AOP in PHP at this point:

It requires less discipline, and you can focus on solving the practical programming tasks rather than trying to architect your way through high-level structural code requirements.

Might be worth 5 minutes of your time, anyway 😉

Therefor the simple solution for me was to do the following.

As you can see it’s very easy to see where object(TestObj) #0 (0) <#_CIRCULAR_REFRENCE_#>came from now. I wanted to keep this debugging code as close to the native var_dump which outputs this.

The difference here is I needed the return as a string, not output to the browser. I also wanted to be able to show class constants, static properties, and private properties ( with flags to change what the debugger outputs, and the depth limit). And, I wanted a bit more information as to what the circular reference was instead of just *RECURSION* which doesn’t tell me anything.

Hope it helps someone in the future.

Here is the full code for my Debug class, you can find this used about line #300

Источник

get_class

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

get_class — Возвращает имя класса, к которому принадлежит объект

Описание

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

Тестируемый объект. Внутри класса этот параметр может быть опущен.

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

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Если параметр object является экземпляром класса, существующего в пространстве имён, то будет возвращено полное имя с указанием пространства имён.

Ошибки

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

ВерсияОписание
7.2.0До этой версии значением по умолчанию для object было null с тем же эффектом, что и отсутствие передачи значения. Теперь null был удалён как значение по умолчанию для object и больше не является допустимым значением.

Примеры

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

// создание объекта
$bar = new foo ();

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

Пример #2 Использование get_class() в родительском классе

class foo extends bar <
>

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

Пример #3 Использование get_class() с классами в пространствах имён

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

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

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

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_class

get_class — Возвращает имя класса, к которому принадлежит объект

Описание

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

Тестируемый объект. Внутри класса этот параметр может быть опущен.

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

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Если параметр object является экземпляром класса, существующего в пространстве имен, то будет возвращено полное имя с указанием пространства имен.

Ошибки

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

ВерсияОписание
7.2.0До этой версии значением по умолчанию для object было null с тем же эффектом, что и отсутствие передачи значения. Теперь null был удален как значение по умолчанию для object и больше не является допустимым значением.

Примеры

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

// создание объекта
$bar = new foo ();

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

Пример #2 Использование get_class() в родительском классе

class foo extends bar <
>

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

Пример #3 Использование get_class() с классами в пространствах имен

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

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

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

Источник

Php get instance of object

A class may contain its own constants, variables (called «properties»), and functions (called «methods»).

Example #1 Simple Class definition

Output of the above example in PHP 7:

Output of the above example in PHP 8:

To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

If there are no arguments to be passed to the class’s constructor, parentheses after the class name may be omitted.

Example #3 Creating an instance

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example #4 Object Assignment

The above example will output:

It’s possible to create instances of an object in a couple of ways:

Example #5 Creating new objects

class Test
<
static public function getNew ()
<
return new static;
>
>

class Child extends Test
<>

The above example will output:

It is possible to access a member of a newly created object in a single expression:

Example #6 Access member of newly created object

The above example will output something similar to:

Note: Prior to PHP 7.1, the arguments are not evaluated if there is no constructor function defined.

Properties and methods

Class properties and methods live in separate «namespaces», so it is possible to have a property and a method with the same name. Referring to both a property and a method has the same notation, and whether a property will be accessed or a method will be called, solely depends on the context, i.e. whether the usage is a variable access or a function call.

Example #7 Property access vs. method call

public function bar () <
return ‘method’ ;
>
>

The above example will output:

That means that calling an anonymous function which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. It is possible to call such a property directly by enclosing it in parentheses.

Example #8 Calling an anonymous function stored in a property

The above example will output:

extends

A class can inherit the constants, methods, and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

The inherited constants, methods, and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

Example #9 Simple Class Inheritance

class ExtendClass extends SimpleClass
<
// Redefine the parent method
function displayVar ()
<
echo «Extending class\n» ;
parent :: displayVar ();
>
>

The above example will output:

Signature compatibility rules

When overriding a method, its signature must be compatible with the parent method. Otherwise, a fatal error is emitted, or, prior to PHP 8.0.0, an E_WARNING level error is generated. A signature is compatible if it respects the variance rules, makes a mandatory parameter optional, and if any new parameters are optional. This is known as the Liskov Substitution Principle, or LSP for short. The constructor, and private methods are exempt from these signature compatibility rules, and thus won’t emit a fatal error in case of a signature mismatch.

Example #10 Compatible child methods

The above example will output:

The following examples demonstrate that a child method which removes a parameter, or makes an optional parameter mandatory, is not compatible with the parent method.

Example #11 Fatal error when a child method removes a parameter

class Extend extends Base
<
function foo ()
<
parent :: foo ( 1 );
>
>

Output of the above example in PHP 8 is similar to:

Example #12 Fatal error when a child method makes an optional parameter mandatory

Output of the above example in PHP 8 is similar to:

Renaming a method’s parameter in a child class is not a signature incompatibility. However, this is discouraged as it will result in a runtime Error if named arguments are used.

Example #13 Error when using named arguments and parameters were renamed in a child class

The above example will output something similar to:

::class

Example #14 Class name resolution

namespace NS <
class ClassName <
>

The above example will output:

The class name resolution using ::class is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.

Example #15 Missing class name resolution

The above example will output:

As of PHP 8.0.0, the ::class constant may also be used on objects. This resolution happens at runtime, not compile time. Its effect is the same as calling get_class() on the object.

Example #16 Object name resolution

The above example will output:

Nullsafe methods and properties

The effect is similar to wrapping each access in an is_null() check first, but more compact.

Example #17 Nullsafe Operator

The nullsafe operator is best used when null is considered a valid and expected possible value for a property or method return. For indicating an error, a thrown exception is preferable.

User Contributed Notes 11 notes

I was confused at first about object assignment, because it’s not quite the same as normal assignment or assignment by reference. But I think I’ve figured out what’s going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object’s «handle» goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

Источник

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

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