Changing the class of an object at runtime

I am working with CMS, Joomla and there is a main class that displays a set of parameters in a JParameter form. It basically has a feature render()

that outputs some HTML that doesn't match the rest of my site.

For maintainability issues and because I have no idea where else this is used, I don't want to change the main code. What would be ideal would be the ability to define a new class that extends JParameter and then move my $ params object into this new subclass.

// existing code --------------------
class JParameter {
    function render() {
        // return HTML with tables
    }
    // of course, there a lot more functions here
}

// my magical class -----------------
class MyParameter extends JParameter {
    function render() {
        // return HTML which doesn't suck
    }
}

// my code --------------------------
$this->params->render();    // returns tables
$this->params = (MyParameter) $this->params;  // miracle occurs here?
$this->params->render();    // returns nice html

      

0


source to share


2 answers


Always PECL Classkit , but I get the feeling you really don't want to do this. Assuming you are calling directly $this->params->render()

, you might just want to create a function / object that does alternate render ( MyParamRenderer::render($this->params)

), and avoid doing OO gymnastics not supported by the language.



+3


source


How about creating a sort decorator that delegates anything apart from JParameter :: render () to an existing object

class MyJParameter {
    private $jparm;
    function __construct( JParameter $jparm ) {
        $this->jparm = $jparm;
    }
    function render() {
        /* your code here */
    }
    function __get( $var ) {
        if( isset( $this->$jparm->$var ) {
            return $this->$jparm->$var;
        }
        return false;
    }
    function __set( $var, $val ) {
        /* similar to __get */
    }
    function __call( $method, $arguments ) {
        if( method_exists( $this->jparm, $method ) {
           return call_user_func_array( array( $this->jparm, $method ), $arguments );
        }
        return false;
    }
}

      



Or is it too smelly?

+2


source







All Articles