Re: Object Casting - An Alternative to Type Hinting

From: Date: Mon, 27 Feb 2012 15:12:44 +0000
Subject: Re: Object Casting - An Alternative to Type Hinting
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-58133@lists.php.net to get a copy of this message
On Sun, February 26, 2012 8:45 pm, Anthony Ferrara wrote: >> Or operator-overlading to the rescue? :-) > > Not quite. Especially because with operator overloading done at this > level (how it would be implemented in PHP) it's almost impossible to > make it consistent: > > class string { > public function overload+($mixed) { > return $this->value + $mixed; I think you meant '.' here instead of '+' Otherwise, PHP type juggling will make it be 10 as well. > } > } > class Integer { > public function overload+($mixed) { > return $this->value + $mixed; > } > } > > $int = new Integer(5); > $string = new String("5"); > > echo $int + $string; // 10 > echo $string + $int; // 55 > > While I like the concept of overloading, I don't really think it's > solvable in a consistent enough manner that it would work here. That said, there is no inconsistency. If what you want to do is overload + on strings to do concatenation, then it's on you to typecast everything to (string) for it to make sense. Oh, and string is a reserved word, so this won't work as-is, though that's obviously picuyane. -- brain cancer update: http://richardlynch.blogspot.com/search/label/brain%20tumor Donate: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FS9NLTNEEKWBE

« previous php.internals (#58133) next »