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

Asked

Viewed 112 times

1

It seems to me that in java there is a way to make Casts to make a particular object instance of another.

Example:

MyClass variable = (MyClass) my_other_class;

In php it is possible to make type cases, and even for object, which in the ALWAYS case is the stdClass.

Example:

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

Now if I have, for example, a class I define and want to give a cast of any value to her, 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?

1 answer

1


According to the PHP Handbook, there are only types of Casts below, these cannot 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

Therefore to be able to convert to an object of a specific class it will be necessary to create a function to do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.