Access class property from outside of class

前端 未结 6 495
感情败类
感情败类 2021-01-22 18:41

Suppose I had the following class:

class MyClass {
    public function Talk() {
        $Say = \"Something\";
        return $Say;
    }
}

I th

6条回答
  •  耶瑟儿~
    2021-01-22 19:08

    The best practices of oop is NEVER have public properties in your class. The best way to manipulate properties of your class is to have separate methods that will return the value of the properties and set the value of the properties. So

    class MyClass {
        private $say;
    
        // common setter, invoked when we trying to set properties as they are public
        public function __set($name, $value) {
            $methodname = 'set' . ucfirst(strtolower($name));
            if (method_exists($this, $methodname)) {
                $this->$methodname($value);
            } else {
                throw new Exception ('There is no "' . $name . '" property in "' . __CLASS__ . '" class');
            }
        }
    
        // common getter, invoked when we trying to get properties as they are public
        public function __get($name) {
            $methodname = 'get' . ucfirst(strtolower($name));
            if (method_exists($this, $methodname)) {
                return $this->$methodname();
            } else {
                throw new Exception ('There is no "' . $name . '" property in "' . __CLASS__ . '" class');
            }
        }
    
        // setter for out private property $say, invoked by common setter when colling $a->say = "something";
        public function setSay($value) {
            $this->say = $value;
        }
    
        // getter for out private property $say, invoked by common getter when colling $a->say;
        public function getSay() {
            return $this->say;
        }
    
        public function Talk($monologue) {
            $this->say = (!empty($monologue))?$this->say:$monologue;
            return $this->say;
        }
    
    }
    

    So now you can access your private properties as they are public, and do all neccessary checks to not get bad values be stored in them. Like that:

    $a = new MyClass;
    $a->say = "Hello my friends !";
    $a->Talk();
    $a->Talk("Good bye !");
    echo $a->say;
    

    Or like that:

    $a = new MyClass;
    $a->setSay("Hello my friends !");
    $a->Talk();
    $a->Talk("Good bye !");
    echo $a->getSay();
    

    For more security, you can make setSay and getSay methods private, but then the second piece of code won't work.

提交回复
热议问题