1

Let's say we have index.php

class Foo_class extends FOOBAR
{
    function __construct()
    {
        require 'some_other_class.php';
        new Some_other_class;

        $this->say_hello();
    }
}

And some_other_class.php

class Some_other_class
{
    function say_hello()
    {
        echo "Wow, it works!";
    }
}

I want, that by including and calling a class Some_other_class in the Foo_class class, Some_other_class class would give Foo_class all of its methods. Is it possible by doing that and not extending? Of course my code will not work.

hakre
  • 193,403
  • 52
  • 435
  • 836
good_evening
  • 21,085
  • 65
  • 193
  • 298

4 Answers4

3

PHP 5.4 comes with a concept of traits which are basically what you're asking for.

Crozin
  • 43,890
  • 13
  • 88
  • 135
1

You don't need to let some_other_class give its methods to Foo_class, you can also get all of its methods with get_class_methods(). Have a look at the PHP Documentation.

So, in your case, you could do something like this:

class Foo_class extends FOOBAR
{

    private $classes = array();

    function __construct()
    {
        $this->register('some_other_class.php');
        $this->say_hello();
    }

    function register($class) {
        require($class);
        $this->classes[$class] = array();
        $c = new $class;
        foreach(get_class_methods($class) as $method) {
            $this->classes[$class][] = $method;
        }
    }

    function __call($name, $arguments) {
        foreach($this->classes as $c_name => $c) {
            foreach($c as $method){
                if($method == $name)
                    call_user_func(array($c_name, $name), $arguments);
            }
        }
    }

}
Sascha Galley
  • 15,711
  • 5
  • 37
  • 51
0

In other, more flexible languages, what you're asking for is called "monkey patching". It's adding (or switching) methods in classes at runtime without resorting to inheritance.

Unfortunately, php won't let you do this.

Community
  • 1
  • 1
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
0

How about using get instance method to invoke remote class method

class Foo_class extends FOOBAR
{
    function __construct()
    {
        require 'some_other_class.php';
        Some_other_class::getInstance()->say_hello();
    }
}

some_other_class.php

class Some_other_class
{

   private static $_selfInstace;

   public static function getInstance() 
    {
        if( !(self::$_selfInstace instanceof self) ) {
            self::$_selfInstace= new self();
        }
        return self::$_selfInstace;
    }

    function say_hello()
    {
        echo "Wow, it works!";
    }
}
Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34