Cannot access private property getset::$name

2019-06-11 07:14发布

问题:

I'm trying to learn the magic methods __GET and __SET. Right now I'm working on the __GET method.

And I'm getting the Cannot Access Private Property error.

Here's my code:

<?php

  class getset {

    private $name;

    public function __set($property, $value) {
      if((property_exists($this, $property))) {
        $this->$property = $value;
        echo "Successfully updated {$property} to {$value}";
      } else {
         echo "This failed.";
      }
    }

  }

  getset::$name = 'Thomas';

?>

I'm not sure what's going on. I've looked at the parameters in a __SET function, and I seem to be following it properly.

I'm not sure what's happening. Here's my full code:

Fatal error: Uncaught Error: Undefined class constant 'name' in C:\xampp\htdocs\OOP Lessons\Classes\getset.inc.php:22 Stack trace: #0 {main} thrown in C:\xampp\htdocs\OOP Lessons\Classes\getset.inc.php on line 22

That line is:

getset::$name = 'Thomas';

回答1:

Here is an example which may help you:

 <?php
      class getset {

        private $name;

        public function __set($property, $value) {
          if((property_exists($this, $property))) {
            $this->$property = $value;
            echo "Successfully updated {$property} to {$value}";
          } else {
             echo "This failed.";
          }
        }

      }
    $newObj=new getset();
    $newObj->name='Thomas';
    print_r($newObj);
?>

//Output:

    Successfully updated name to Thomas

    getset Object
    (
       [name:getset:private] => Thomas
    )


标签: php oop