-1

I'm currently looking for a way to set a new instance to be the same as an exists instance if already exists.

Is there any easy way as doing something like:

Class Check { public static $instance = null; public $name = ""; function __construct($name) { if (self::$instance !== null) { $this = self::$instance; } else { $this->name = $name; self::$instance = $this; } } } $a = new Check("A"); $b = new Check("B"); echo $a->name." = ".$b->name; 

to achieve it?

what it returns:

A = 

What I want it to return:

A = A 

Is it possible to accomplish that? I want that all variables of the older instance to maintain the same.

Thanks in advance.

6
  • 2
    Do you mean stackoverflow.com/questions/24852125/what-is-singleton-in-php/… Commented Aug 29, 2021 at 12:40
  • 1
    No. Assigning to $this doesn't change the instance itself. Implement a singleton class with a method that returns self::$instance. Commented Aug 29, 2021 at 12:40
  • @Barmar Yea I've saw it and edited my question. but you can understand my needs from the question. I know I can't do it like that.. but is there any easy option like what I've showed. Commented Aug 29, 2021 at 12:42
  • @NigelRen Well, like a singleton class.. But I want to do it using "new Class" and not by Class::getInstance Commented Aug 29, 2021 at 12:44
  • If you have static variables, they will be shared between all classes, is there any reason why you need this? Commented Aug 29, 2021 at 13:20

1 Answer 1

0

This is the only two ways I found to achieve it

#1 Using get_object_vars

You can use get_object_vars that returns all public variables that a specific object contains, then you can iterate them using foreach

example:

if (self::$instance !== null) { foreach (get_object_vars(self::$instance) as $prop=>$value) { $this->{$prop} = $value; } } 

#2 Is using PHP reflection, I find it less useful in my case because it doesn't reflect properties that was generated on the go

Note: Reflection will reflect also properties such as private|static and so. you can filter them inside the getProperties function or iterate through all properties and use boolean methods filter between them.

example:

if (self::$instance !== null) { $reflection = new ReflectionClass(self::$instance); $props = $reflection->getProperties(); foreach ($props as $prop) { $this->{$prop->name} = $prop->getValue(self::$instance); } } 

so if you do self::$instance->newVar = 1; it won't be reflected. but in the #1 Option it will be.

Hope it will help someone out there.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.