3

In javascript, we can edit the prototype of objects like string and numbers and simply "add functions" to already existing native classes.

I was wondering how do we "add functions" to already existing php native classes (like strings etc) ?

5
  • 4
    By the way, there isn't a string class in PHP. It's a primitive data type. Commented Oct 12, 2011 at 21:37
  • @BoltClock k cool, thx for the info =D Commented Oct 12, 2011 at 21:41
  • 1
    For user-defined classes, there is runkit: php.net/manual/de/book.runkit.php ... but you can't modify built-in classes with this. In my opinion it's not good practice, anyway ... if you want to extend a (native) class, just extend it ;-) Commented Oct 12, 2011 at 22:23
  • 1
    By way of clarification, the same is true of most other built-in types (e.g, strings, numbers, arrays, file handles, etc). PHP was originally designed without classes, so most of its basic functionality is not object-oriented. Commented Oct 12, 2011 at 23:34
  • @harald no no, you are missing the point. I wanna do this: "a string".Action(). we can do this in javascript and in vb.net Commented Oct 13, 2011 at 1:06

1 Answer 1

4

You can't do that in PHP. You can only inherit from the existing classes (if they're not final) and add methods to the subclasses.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd thought dynamic PHP is supposed to have this feature. Dang, even vb.net allows us to add methods onto already existing classes without subclassing it
@Pacerier: Extension methods in C# and VB.NET don't actually modify the original classes, even though it looks as if they do. But good point.
Maybe it's just me, but it seems more in line with OOP to extend a class through inheritance anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.