How do I add a method to an object in PHP?
class, oop, php
Solution
A solution would be to create a new class, that extends the one from your library -- and, then, use your class, which have have all methods of the original one, plus yours.
Here's a (very quick and simple) example :
class YourClass extends TheLibraryClass {
public function yourNewMethod() {
// do what you want here
}
}
And, then, you use your class :
$obj = new YourClass();
$obj->yourNewMethod();
And you can call the methods of the `TheLibraryClass` class, as yours inherits the properties and methods of that one :
$obj->aMethodFromTheLibrary();
About that, you can take a look at the Object Inheritance section of the manual.
And, as you guessed, modifying a library is definitly a bad idea : you'll have to re-do that modification each time you update the library !
(One day or another, you'll forget -- or one of your colleagues will forget ^^ )
Problem
I've got an Object Oriented library I wanted to add a method to, and while I'm fairly certain I could just go into the source of that library and add it, I imagine this is what's generally known as A Bad Idea. How would I go about adding my own method to a PHP object correctly? UPDATE ** editing ** The library I'm trying to add a method to is simpleHTML, nothing fancy, just a method to improve readability. So I tried adding to my code: ``` class simpleHTMLDOM extends simple_html_dom { public function remove_node() { $this->outertext = ""; } } ``` which got me: `Fatal error: Call to undefined method simple_html_dom_node::remove_node()`. So obviously, when you grab an element in simpleHTML it returns an object of type simple_html_dom_node. If I add the method to `simple_html_dom_node` my subclass isn't what will be created by simplHTML ... so stuck as to where to go next.