Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a method to an existing class in PHP?

Tags:

I'm using WordPress as a CMS, and I want to extend one of its classes without having to inherit from another class; i.e. I simply want to "add" more methods to that class:

class A {      function do_a() {        echo 'a';     } } 

then:

function insert_this_function_into_class_A() {     echo 'b'; } 

(some way of inserting the latter into A class)

and:

A::insert_this_function_into_class_A();  # b 

Is this even possible in tenacious PHP?

like image 723
Gal Avatar asked Jun 10 '10 05:06

Gal


People also ask

How do you call a class method in PHP?

When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

What is __ method __ in PHP?

"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.


1 Answers

If you only need to access the Public API of the class, you can use a Decorator:

class SomeClassDecorator {     protected $_instance;      public function myMethod() {         return strtoupper( $this->_instance->someMethod() );     }      public function __construct(SomeClass $instance) {         $this->_instance = $instance;     }      public function __call($method, $args) {         return call_user_func_array(array($this->_instance, $method), $args);     }      public function __get($key) {         return $this->_instance->$key;     }      public function __set($key, $val) {         return $this->_instance->$key = $val;     }      // can implement additional (magic) methods here ... } 

Then wrap the instance of SomeClass:

$decorator = new SomeClassDecorator(new SomeClass);  $decorator->foo = 'bar';       // sets $foo in SomeClass instance echo $decorator->foo;          // returns 'bar' echo $decorator->someMethod(); // forwards call to SomeClass instance echo $decorator->myMethod();   // calls my custom methods in Decorator 

If you need to have access to the protected API, you have to use inheritance. If you need to access the private API, you have to modify the class files. While the inheritance approach is fine, modifiying the class files might get you into trouble when updating (you will lose any patches made). But both is more feasible than using runkit.

like image 158
Gordon Avatar answered Sep 21 '22 16:09

Gordon