By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,087 Members | 1,521 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,087 IT Pros & Developers. It's quick & easy.

Does PHP have an equivalent of JavaScript's prototype object?

P: n/a
Basically, I want to add default methods to the PHP string object so
that I can do something like:

$stringvar = "hello";

$stringvar -> append(" world"); // where append is some kind of
prototyped function i define

echo $stringvar; // "hello world"

is this at all possible?

thanks!!

Nov 22 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
al*******@gmail.com wrote:
Basically, I want to add default methods to the PHP string object so
that I can do something like:

$stringvar = "hello";

$stringvar -> append(" world"); // where append is some kind of
prototyped function i define

echo $stringvar; // "hello world"

is this at all possible?

thanks!!


Hi,

AFAIK you cannot easily extend the existing String in PHP.
(You would have to dive into the sourcecode, modify it, and recompile)

But you can of course create your own wrapper-object.
Just create a new class MyString and extend it to your liking with methods
you like.

Regards,
Erwin Moller
Nov 22 '05 #2

P: n/a
al*******@gmail.com wrote:
Basically, I want to add default methods to the PHP string object so
that I can do something like:

$stringvar = "hello";

$stringvar -> append(" world"); // where append is some kind of
prototyped function i define

echo $stringvar; // "hello world"

is this at all possible?


No for two reasons:

1) PHP has primitive types which are not objects (strings, integers, floats,
arrays).

2) Unlike javascript, a PHP class cannot be modified at runtime.

Of course there is nothing to stop you creating a class and manipulating the
data in an instance using a function or a seperate class.

C.
Nov 22 '05 #3

P: n/a
Thanks Erwin and Colin for the info. Hmm, is that one more reason to
switch to Ruby? =)

Nov 22 '05 #4

P: n/a
al*******@gmail.com schrieb:
Basically, I want to add default methods to the PHP string object so
that I can do something like:

$stringvar = "hello";

$stringvar -> append(" world"); // where append is some kind of
prototyped function i define

echo $stringvar; // "hello world"

is this at all possible?


Surprise: There ain't even a string object!
PHP is all about speed through native code.
So strings are primitive types.

But for your example, as for most of the common string operations:
Do not reinvent the wheel! All common string manipulation functions are
already implemented as fast compiled C-code...

$stringvar='hello';
$stringvar.=' world';

OLLi
Nov 22 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.