繁体   English   中英

无法访问私有属性getset :: $ name

[英]Cannot access private property getset::$name

我正在尝试学习魔术方法__GET和__SET。 现在,我正在使用__GET方法。

我收到了“无法访问私有财产”错误。

这是我的代码:

<?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';

?>

我不确定发生了什么。 我已经看过__SET函数中的参数,并且似乎正确地遵循了它。

我不确定发生了什么。 这是我的完整代码:

致命错误:未捕获错误:C:\\ xampp \\ htdocs \\ OOP Lessons \\ Classes \\ getset.inc.php:22中未定义的类常量“名称”第22行的Lessons \\ Classes \\ getset.inc.php

该行是:

getset::$name = 'Thomas';

这是一个可以帮助您的示例:

 <?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);
?>

//输出:

    Successfully updated name to Thomas

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM