PHP's type juggling, does it work with object's __toString() magic method?
Well in PHP, the below code defines number as string types but when you use plus, minus, multiply or other algorithmic operators they are converted to the corresponding number types:
An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer.
What you need to be doing instead is adding some math methods to you objects, or referencing the values directly:
PHP Code:
$sum = $byte->theValue() + $double->theValue(); // etc.
I do have a Math class with a group of static methods to do these, but I was wondering if there were easier ways. Anyway nvm, it is just an experience I am conducting, PHP clearly aint like ruby in which everything is an object so some techniques do not work.
I suppose that if you had the __toString() method return a numeric string, you could do something (kind of ugly) like:
PHP Code:
$total = $someNumber + (string)$someObject;
But that seems a rather obfuscating thing to do -- not something I'd care to run into when maintaining that code a year later, even if I didn't have to prepend the (string) part. Much easier to read would be:
Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett
"But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html
Bookmarks