Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an integer equivalent of __toString()

Tags:

php

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.

like image 382
Michael Clerx Avatar asked Sep 20 '10 12:09

Michael Clerx


People also ask

What is toString 36 in Javascript?

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.

What is toString 16 in JS?

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.


1 Answers

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.

like image 132
user228395 Avatar answered Sep 20 '22 19:09

user228395