PHP 多个特征中的同名魔术方法

问题描述 投票:0回答:1

相同魔法方法的特性冲突如何解决?

特征和扩展类中的所有 __get 方法都应该可用。理想情况下,我希望 Foo::__get 优先于 Bar::__get,Bar::__get 优先于 Test::__get。

trait Foo {
    public function __get($name)
    {
        if (str_ends_with($name, 'Foo')) {
            return 'Foo';
        }

        return parent::__get($name);
    }
}

trait Bar {
    public function __get($name)
    {
        if (str_ends_with($name, 'Bar')) {
            return 'Bar';
        }

        return parent::__get($name);
    }
}

class Test {
    public function __get($name)
    {
        if (str_ends_with($name, 'Test')) {
            return 'Test';
        }

        null;
    }
}

class FooBar extends Test {
    use Foo, Bar; //What to do here to resolve issues?
}

$instance = new FooBar();
$instance->propertyFoo; //"Foo"
$instance->propertyBar; //"Bar"
$instance->propertyTest; //"Test"
$instance->propertyDemo; //null
php traits
1个回答
0
投票

如果您想解决冲突,您需要阅读手册。但根据你的描述,你需要解决的不是冲突,而是一个非常具体的问题。而且不幸的是,因为你在

__get
中调用了父类的
Foo::__get
方法,所以你不能简单地依次调用它们。最后,我们需要先检查
Foo::__get
的返回值:

class FooBar extends Test {
    use Foo, Bar {
        Foo::__get as fooget;
        Bar::__get as barget;
    }
    
    public function __get($name) {
        $ret = $this->fooget($name);
        return $ret != 'Foo' ? $this->barget($name) : $ret;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.