从特质访问父魔法
问题描述:
I'm trying to redefine the behaviour of the magic method __set
in a trait. The problem shows up when I also want to access from the trait to the parent class custom __set
function.
trait TestingTrait {
public function __set($key, $value)
{
// Some stuff...
parent::__set($key, $value);
// self::__set($key, $value);
}
}
class TestingClass {
use TestingTrait;
}
$var = new TestingClass();
$var->value = 'some value';
Everything works perfect until I need to also use the main class __set
method as it's doing some other stuff with the variable sets.
I've tried with self
but it goes into an infinite loop. Is there any way to access the main class?
答
You're supposed to use $this->
like this:
<?php
trait TestingTrait {
public function __set($key, $value)
{
// Some stuff...
$this->$key = 'proof that it is going through here: ' . $value;
}
}
class TestingClass {
use TestingTrait;
}
$var = new TestingClass();
$var->value = 'some value';
echo $var->value;
proof that it is going through here: some value
答
I didn't know traits behaviour is as if it were a portion of code literally copy/pasted into the class.
It's not possible to access the main class via parent as it actually have no parent extending from.