Function of objects that return specific values ​​when moving an object

First of all, I apologize that this question is so vague. I don’t remember what it is called, or how they work, so it’s very difficult to start a search or formulate a good headline.

I have two questions enclosed in one:

Firstly:

How do objects internally convert to other types? What is called?

Example:

$Obj{ $value = 1; $other = 2; $more = 3; } $myObj = (string)$Obj; print $myObj; // prints "1, 2, 3" or something like that 

Secondly:

Can this method be used in mathematics? Is there an override function that recognizes when an object is used in math?

Example:

 $Obj{ $value = 1; $other = 2; $more = 3; } $result = 4 / $Obj; print $result; // prints ".66666667" or something similar (sum of all properties) 

Update:

I think this might have something to do with serialize () , but I know that I heard about the case when this is done “automatically” without calling serialize() and so that it serializes the whole object, it just converts its useful value, like my examples above.

The final:

Thanks for @trey for being right about casting and @webbiedave to point out the magic of the __ toString method.

+4
source share
2 answers

This is a cast , since you can define the __ toString magic method to allow the object to be wrapped to a string as desired, which will then allow PHP to pass it to an int or float in math.

Take the following example:

 class A { public $value = 1; public $other = 2; public $more = 3; public function __toString() { return (string)($this->value + $this->other + $this->more); } } $obj = new A(); echo 4 / (string)$obj; // outputs 0.66666666666667 
+4
source

He called type casting, when you change an object to another data type, as in the second part, I'm not quite sure that I understand you, are you trying to introduce a cast during a mathematical function?

it looks like this might be more in line with what you are looking for:

 class User { public $first_name='John'; public $last_name='Smith'; public function __toString() { return "User [first='$this->first_name', last='$this->last_name']"; } } $user=new User; print '<span>'.$user.'</span>'; 

but I can’t find the documentation on how to make this work when the object is converted to interger ... I will update if I do

+3
source

All Articles