PHP:获取类

时间:2015-09-02 11:12:50

标签: php class methods private

过去几个小时我一直用PHP做项目,遇到了一个问题。

问题是我不知道如何访问类中的私有变量而我无法在线找到它。

示例:

<?php
    class Example{
        private $age;

        public function __construct() {
            $age = 14;
            $this->checkAge();
        }
        private function checkAge() {
            if($this->$age > 12)
                echo "welcome!";
        }
    }
    $boy = new Example();
?>

据我所知,我应该能够使用$ this-&gt; $ age访问该变量,但它无效。

谢谢。

编辑:得到了令人敬畏的stackoverflooooooooow社区的帮助,这就是一个正常工作的人。

<?php
    class Example{
        private $age;

        public function __construct() {
            $this->age = 14;
            $this->checkAge();
        }
        private function checkAge() {
            if($this->age > 12)
                echo "welcome!";
        }
    }
    $boy = new Example();
?>

1 个答案:

答案 0 :(得分:0)

看看这种方法。
第一个:创建在私有$ attributes数组中存储和检索数据的实体,并使用magic __set(),__ get()你也可以这样做:$ object-&gt; variable = 123

第二个:使用Human类扩展Entity并添加一些特定于子类的函数(例如hasValidAge()):

<?php
    class Entity {
        private $attributes;

        public function __construct($attributes = []) {
            $this->setAttributes($attributes);
        }

        public function setAttribute($key, $value) {
            $this->attributes[$key] = $value;
            return $this;
        }

        public function setAttributes($attributes = []) {
            foreach($attributes AS $key => $value) {
              $this->setAttribute($key, $value);
            }
        }

        public function getAttribute($key, $fallback = null) {
            return (isset($this->attributes[$key]))? 
                   $this->attributes[$key] : $fallback;
        }

        public function __get($key) {
            return $this->getAttribute($key);
        }

        public function __set($key, $value) {
            $this->setAttribute($key, $value);
        }
    }

    class Human extends Entity {
        public function __construct($attributes = []) {
            $this->setAttributes($attributes);
            $this->checkAge();
        }

        public function hasValidAge() {
            return ($this->getAttribute('age') > 12)? true : false;
        }
    }

    $boy = new Human(['name' => 'Mark', 'age' => 14]);
    if($boy->hasValidAge()) {
        echo "Welcome ".$boy->name."!";
    }

?>

P.S。我删除了回音“欢迎!”部分来自构造函数,因为从模型对象做回声并不酷,在我们的示例中,Human是Entity的模型。