Using undefined property in php class

<?php
class a{
    public function out(){
        $this->test = 8;
        return $this->test;
    }
}
$b = new a();
echo $b->out();
?>

output: 8

when I run this code, output the result 8.

but when I add the __set () function, it gives a notification, not 8 output

<?php
class a{
    public function __set($property, $value) {  
    }
    public function out(){
        $this->test = 8;
        return $this->test;
    }
}
$b = new a();
echo $b->out();
?>

conclusion:

PHP Note: Undefined property: a :: $ test in /usercode/file.php on line 13

Why is this happening?

+4
source share
3 answers

When a::out()executed, the object does not have a property $test. That is why it $this->test = 8;causesa::__set() .

But it a::__set()does not create a property $test, and the next statement ( return $this->test;) cannot find it and issues a notification.

You must declare the properties of the object in the class definition and initialize them in the constructor (if necessary):

class a {
    private $test;               // <-- because of this, $this->test exists...

    public function __set($property, $value) {  
    }

    public function out() {
        $this->test = 8;         // ... and __set() is not invoked here
        return $this->test;
    }
}

__set() $this->test = 8; $test , ( ), 8 .

__set() , , ( a private, , protected private ) __set(). __set() $this->test = 8; no-op.

+4

docs

__ set() .

__set, , , . .

class a{
    public function __set($property, $value) {
        $this->$property = $value;
    }
    public function out(){
        $this->test = 8;
        return $this->test;
    }
}
$b = new a();
echo $b->out();

THAT 8.

, , - . PHP , .

, __set() , $this->test, PHP __set(), , : .

__set() , __set() . - __set(), .

+4

The following is true:

<?php
class a{
    public function __set($property, $value) {
        $this->$property = $value;
    }
    public function out(){
        $this->test = 8;
        return $this->test;
    } 
}
$b = new a();
echo $b->out();  

you should look at php overload

Find the answers in the manual.

+1
source

Source: https://habr.com/ru/post/1692694/


All Articles