Re: Class & Type Casting

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, Jun 10, 2008 at 5:13 AM, Leurent Francois <131.php@xxxxxxxxxxxx>
wrote:

> I was asking myself if there was a good reason this syntax not to work
>
> class string_extented{
> function __construct($str){
> $this->contents=$str;
> }
> function __toString(){
> return $this->contents;
> }
>
> }
>
> //that's working fine
> $test= new string_extended("this is my anonymous string");
> echo $test;
>
>
> /that's not working, but should'nt it be the case ?
> $test = (string_extended) "This is my anonymous string";
> echo $test;
>
> I'll find this very usefull :x, it's just a syntax ehancement nope ?


in some languages, such as java, the syntax "", is merely syntactic sugar
for creating an instance of a class, say String.  in such languages creating
a subclass of String, would give you the ability to cast in the way you have
done.  however, in php a string is a primitive type and nothing more,
therefore the above will not work.

furthermore, i dont see what enhancement youre adding to strings in the code
fragment is anyway.  you can still pass around string variables and echo
them at any time.  one thing i have used __toString() for is in a subclass
of SimpleXMLElement, where SimpleXMLElement::asXML() returns a string
representation of the instance, i have added

public function __toString() {
  return $this->asXML();
}

to make it a bit more elegant, imho ;)

and lastly, as a side note / mini rant; since ive been mumbling about java
so much lately, i would like to take a second to mention that objective-c,
in particular the apple cocoa framework, is another language that supports a
string literal syntax for a class.  an NSString instance can be represented
literally by @""; and im sure there are other examples out there as well.

-nathan

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux