How to simulate a cast of a class in PHP (other than stdClass)?

1

It seems to me that in java there is a way to make casts to make a given object instance another.

Example:

MyClass variable = (MyClass) my_other_class;

In php it is possible to do casts of types, and even for object, which in the case is ALWAYS the stdClass .

Example:

$int = 1;
$object = (object) $int;
$array = (array) $int;
$str = (string) $int;

Now if I have, for example, a class that I defined and want to give a cast of any value to it, it is not possible.

Example:

$arr = array();

$obj = (object) $arr; // Retorna: stdClass

$myObj = (MyObject) $arr; // Retorna: Parse Error

Is there any way to simulate this in PHP?

    
asked by anonymous 05.08.2015 / 18:04

1 answer

1

According to the PHP Manual, there are only the casts types below, which can not be natively customized:

  • (bool) or (boolean) = Converting to Boolean
  • (int) or (integer) = Converting to integer
  • (float) = Converting to float
  • (string) = Converting to string
  • (array) = Converting to array
  • (object) = Converting to object (this will always be stdClass )
  • (resource) = Converting to resource
  • (unset) = Converting to NULL

So to be able to convert to an object of a specific class you will need to create a function to do this.

    
05.08.2015 / 18:32