Is there a way to tell PHP how to convert your objects to ints? Ideally it would look something like
class ExampleClass { ... public function __toString() { return $this->getName(); } public function __toInt() { return $this->getId(); } }
I realize it's not supported in this exact form, but is there an easy (not-so-hacky) workaround?
---------------------- EDIT EDIT EDIT -----------------------------
Thanks everybody! The main reason I'm looking into this is I'd like to make some classes (form generators, menu classes etc) use objects instead of arrays(uniqueId => description). This is easy enough if you decide they should work only with those objects, or only with objects that extend some kind of generic object superclass.
But I'm trying to see if there's a middle road: ideally my framework classes could accept either integer-string pairs, or objects with getId() and getDescription() methods. Because this is something that must have occurred to someone else before I'd like to use the combined knowledge of stackoverflow to find out if there's a standard / best-practice way of doing this that doesn't clash with the php standard library, common frameworks etc.
This parameter specifies the base in which the integer is represented in the string. It is an integer between 2 and 36 which is used to specify the base for representing numeric values. Return Value: The num. toString() method returns a string representing the specified number object.
The toString() method parses its first argument, and attempts to return a string representation in the specified radix (base). For radices above 10 , the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), a through f are used.
I'm afraid there is no such thing. I'm not exactly sure what the reason is you need this, but consider the following options:
Adding a toInt()
method, casting in the class. You're probably aware of this already.
public function toInt() { return (int) $this->__toString(); }
Double casting outside the class, will result in an int.
$int = (int) (string) $class;
Make a special function outside the class:
function intify($class) { return (int) (string) $class; } $int = intify($class);
Of course the __toString()
method can return a string with a number in it: return '123'
. Usage outside the class might auto-cast this string to an integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With