Can anyone please explain me a logic in this behaviour?
Consider the following situation:
class EPPDomain
{
protected $myField;
public static function buildEPPDomain($fieldValue)
{
$me = new self();
$me->myField = $fieldValue;
return $me;
}
public function __set($name, $value)
{
$this->$name = "prefix_".value;
}
}
class EPPDomainFactory
{
public static function buildEPPDomain($fieldValue)
{
$me = new EPPDomain();
$me->myField = $fieldValue;
return $me;
}
}
So
$dmn = EPPDomain::buildEPPDomain("myValue");
echo $dmn->myField;
Expected
prefix_myValue
Actual
myValue
Obviously,
$dmn = EPPDomainFactory::buildEPPDomain("myValue");
echo $dmn->myField;
Works as expected outputting
prefix_myValue
According to __set description on http://www.php.net/manual/en/language.oop5.overloading.php#object.set
__set() is run when writing data to inaccessible properties.
When I create an instance of EPPDomain in a static method of EPPDomain class all protected properties are supposed to be inaccessible. Therefore __set should be called but it is not
I know it also says
Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.
But I have an inpression that it just states that __set method should be a class member function and should not be static. That is it and it seems it has nothing to do with the situation I am facing.
Is that a bug or expected behaviour?
__set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties.
__call() is triggered when invoking inaccessible methods in an object context. __callStatic() is triggered when invoking inaccessible methods in a static context. The $name argument is the name of the method being called.
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that. __FUNCTION__ returns only the name of the function. while as __METHOD__ returns the name of the class alongwith the name of the function.
A protected
property is accessible to all code in the same or inheriting classes. The emphasis being on class.
class Foo {
protected $bar;
public function foo() {
$foo = new self;
$foo->bar = 'baz';
}
}
This works just fine. The class is working on an instance of itself, it has access to its own properties. It's not about "foreign instances", it's about the class.
The point of protected properties is that their presence or implementation should only be relevant to the class that defines them. Other code shouldn't mess with them directly. Since one can assume that a class knows how to deal with its own properties, a class is trusted to manipulate properties of any object of its type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With