从其他类传递方法到类

时间:2011-09-02 15:06:44

标签: php oop

假设我们有index.php

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

        $this->say_hello();
    }
}

和some_other_class.php

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

我希望,通过在Some_other_class课程中加入和调用课程Foo_classSome_other_class课程将为Foo_class提供所有方法。这样做是否可能而不是延伸?当然我的代码不起作用。

4 个答案:

答案 0 :(得分:3)

PHP 5.4带有traits的概念,基本上就是你所要求的。

答案 1 :(得分:1)

您无需让some_other_class将其方法提供给Foo_class,您也可以使用get_class_methods()获取所有方法。有一个look at the PHP Documentation

所以,在你的情况下,你可以这样做:

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);
            }
        }
    }

}

答案 2 :(得分:0)

在其他更灵活的语言中,您要求的内容称为“猴子修补”。它在运行时在类中添加(或切换)方法,而不依赖于继承。

不幸的是,php won't let you do this

答案 3 :(得分:0)

如何使用get实例方法调用远程类方法

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!";
    }
}