Php get class instance

How to get instance of a specific class in PHP?

It suggests that you have a deeper misunderstanding about the purpose of objects and classes. Solution 1: Use: Solution 2: for static classes or for instantiated. , as Jason said, was introduced in PHP 5.3 Solution 3: You can simply use: Question: I would like to get all the instances of an object of a certain class.

How to get instance of a specific class in PHP?

I need to check if there exists an instance of class_A ,and if there does exist , get that instance.

As always, I think a simple example is best.

Now my problem has become:

How to store the instance in a static member variable of class_A when instantiating?

It’ll be better if the instance can be stored when calling __construct() . Say, it should work without limitation on how it’s instantiated.

What you have described is essentially the Singleton pattern . Please see this question for good reasons why you might not want to do this.

If you really want to do it, you could implement something like this:

class a < public static $instance; public function __construct() < self::$instance = $this; >public static function get() < if (self::$instance === null) < self::$instance = new self(); >return self::$instance; > > $a = a::get(); 

What you ask for is impossible (Well, perhaps not in a technical sense, but highly impractical). It suggests that you have a deeper misunderstanding about the purpose of objects and classes.

You should implement the Singleton pattern. http://www.developertutorials.com/tutorials/ php/php-singleton — design-pattern -050729/page1.html

Maybe you want something like

for (get_defined_vars() as $key=>$value)

EDIT: Upon further reading, you have to jump through some hoops to get object references. So you might want return $$key; instead of return $value; . Or some other tricks to get a reference to the object.

Php — Getting DOM elements by classname, Update: Xpath version of *[@class~=’my-class’] css selector. So after my comment below in response to hakre’s comment, I got curious and looked into the code behind Zend_Dom_Query.It looks like the above selector is compiled to the following xpath (untested):

How to obtain class name in a static method in PHP?

Actually my problem is more complicated than the title says.

I want to have a base class with a static method , and the method should be able to obtain the class name of the current class.

class Base < public static function className() < return '. '; >> class Foo extends Base < >echo Foo::className(); 

I expect Foo to be the output.

Читайте также:  Php enable exif extension

As some pointed out that in php5.5 it is simple with static::class , I should say I have to use PHP5.3 allowing for the framework we are using. 🙁

You can use static::class since PHP 5.5, like this:

Simply Try this following with static::class or get_called_class() both will return the Class name from which class calling this static method

 > class Foo extends Base < >class Doo extends Base < >echo Foo::className(); // Output will be Foo echo Bar::className(); // Output will be Bar 

For PHP >=5.3 you can use get_called_class() .

Example copied from http://php.net/get_called_class

 > class bar extends foo < >print foo::test(); print bar::test(); ?> 

The above example will output:

PHP | get_class_methods() Function, A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh — 201305

Get class name from extended class

Is it possible to get the name of the top level class from an extended class, without setting it from the top level class. See example below, I would like to get ‘Foo’ from Base. I know I could set a variable from Foo, but hoping to skip the extra step.

class Base < function __construct() < echo '

get_class: '.get_class().'

'; echo '

__CLASS__: '.__CLASS__.'

'; > > class Foo extends Base < >$test = new Foo();

get_called_class() for static classes or get_class($this) for instantiated.

get_called_class() , as Jason said, was introduced in PHP 5.3

__get and __set magic methods, A better solution is a base class and interface for when extending other classes, so you can just copy the few lines of code from the base class into the implementing class. I’m doing a bit more with my project’s base class, so I don’t have an interface to provide right now, but here is the untested stripped down …

Get all instances of a class in PHP

I would like to get all the instances of an object of a certain class.

class Foo < >$a = new Foo(); $b = new Foo(); $instances = get_instances_of_class('Foo'); 

$instances should be either array($a, $b) or array($b, $a) (order does not matter).

A plus is if the function would return instances which have a superclass of the requested class, though this isn’t necessary.

One method I can think of is using a static class member variable which holds an array of instances. In the class’s constructor and destructor, I would add or remove $this from the array. This is rather troublesome and error-prone if I have to do it on many classes.

If you derive all your objects from a TrackableObject class, this class could be set up to handle such things (just be sure you call parent::__construct() and parent::__destruct() when overloading those in subclasses.

class TrackableObject < protected static $_instances = array(); public function __construct() < self::$_instances[] = $this; >public function __destruct() < unset(self::$_instances[array_search($this, self::$_instances, true)]); >/** * @param $includeSubclasses Optionally include subclasses in returned set * @returns array array of objects */ public static function getInstances($includeSubclasses = false) < $return = array(); foreach(self::$_instances as $instance) < if ($instance instanceof get_class($this)) < if ($includeSubclasses || (get_class($instance) === get_class($this)) < $return[] = $instance; >> > return $return; > > 

The major issue with this is that no object would be automatically picked up by garbage collection (as a reference to it still exists within TrackableObject::$_instances ), so __destruct() would need to be called manually to destroy said object. (Circular Reference Garbage Collection was added in PHP 5.3 and may present additional garbage collection opportunities)

Читайте также:  Java library path gradle

Here’s a possible solution:

function get_instances_of_class($class) < $instances = array(); foreach ($GLOBALS as $value) < if (is_a($value, $class) || is_subclass_of($value, $class)) < array_push($instances, $value); >> return $instances; > 

Edit : Updated the code to check if the $class is a superclass.

Edit 2 : Made a slightly messier recursive function that checks each object’s variables instead of just the top-level objects:

function get_instances_of_class($class, $vars=null) < if ($vars == null) < $vars = $GLOBALS; >$instances = array(); foreach ($vars as $value) < if (is_a($value, $class)) < array_push($instances, $value); >$object_vars = get_object_vars($value); if ($object_vars) < $instances = array_merge($instances, get_instances_of_class($class, $object_vars)); >> return $instances; > 

I’m not sure if it can go into infinite recursion with certain objects, so beware.

I need this because I am making an event system and need to be able to sent events to all objects of a certain class (a global notification, if you will, which is dynamically bound ).

I would suggest having a separate object where you register objects with (An observer pattern). PHP has built-in support for this, through spl; See: SplObserver and SplSubject.

As far as I know, the PHP runtime does not expose the underlying object space, so it would not be possible to query it for instances of an object.

Php — Get class name from extended class, Is it possible to get the name of the top level class from an extended class, without setting it from the top level class. See example below, I would like to get ‘Foo’ from Base. I know I could set a variable from Foo, but hoping to skip the extra step. Thanks. class Base < function __construct() < echo '

get_class: …

Источник

How to get class instance without a constructor in PHP

Have you ever stumbled upon a situation in which you need an instance of a class to create its object but with one condition and that is there is no constructor declared for that class?

The problem

I did encounter this while working on one of my PHP packages called array-utils.

So, the package is just a simple library which is a wrapper implementation of common PHP array methods. I created this package because I wanted uniformity across these different array methods. Because the PHP methods have parameter inconsistency among them, it would be great if it could be streamlined a little bit. And so, I started working on this package.

Читайте также:  Memory manager in java

I wanted to design the package the same way how the Laravel collections works. Essentially, to collect the array and calling array methods fluently on it.

For this to be done, one thing was clear that the class (The ArrayUtils class in this case) that I would create would not have a constructor. Because, if it would have a constructor, it would be absolutely necessary to create an object of this class to use it further.

I did not want that. I needed a way using which the user can simply call a class method to create a class instance.

The solution

Turns out, you can do this by using a static method and return the class instance from it.

Here’s how I did it for my package.

namespace Amitmerchant\ArrayUtils; class ArrayUtils  // code commented for brevity /** * Returns the class instance * * @return \AmitMerchant\ArrayUtils\ArrayUtils */ public static function getInstance()  return new ArrayUtils(); > // code commented for brevity > 

As you can tell, the static getInstance method returns the instance of the class here. This makes it to get a class instance when using the package like so.

ArrayUtils::getInstance(); // returns instance of the class 

And that’s it! It’s now fairly easy to call any class methods fluently on this.

Here’s a slightly expanded version of the ArrayUtils class.

namespace Amitmerchant\ArrayUtils; use Closure; class ArrayUtils  private $collection; /** * Returns the class instance * * @return \AmitMerchant\ArrayUtils\ArrayUtils */ public static function getInstance()  return new ArrayUtils(); > /** * Collects the input array * * @param array $collection * @return $this */ public function collect(array $collection)  $this->collection = $collection; return $this; > /** * Wrapper method for array_map * * @param Closure $closure * @return mixed */ public function map(Closure $closure)  return array_map($closure, $this->collection); > > 

As you can tell, the class now has two new methods called collect and map . These methods can be called fluently using the getInstance method like so.

use Amitmerchant\ArrayUtils\ArrayUtils; $mappedArray = ArrayUtils::getInstance() ->collect([1, 2, 3, 4]) ->map(function($iteration)  return $iteration * 2; >) 

And that is how you can get the class instance without having the class constructor!

PHP 8 in a Nutshell book cover

PHP 8 in a Nutshell book cover

Learn the fundamentals of PHP 8 (including 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It’s a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you’re looking for a quick and easy way to PHP 8, this is the book for you.

Caricature of Amit Merchant sketched by a friend

👋 Hi there! I’m Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I’d highly appreciate that. Cheers!

Источник

Оцените статью