Access class property from outside of class

前端 未结 6 446
感情败类
感情败类 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:03

    You need to make the $Say an instant variable of the MyClass class.

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

    You could then access the instance variable from outside the class via $Inst->Say

    Additionally it is better practice to encapsulate your class instance variables and use a "getter" method to retrieve the values.

    class MyClass {
        private $Say
        public function Talk() {
            $this->Say = "Something";
            return $this->Say;
        }
        public getSay() {
            return $this->Say;
        }
    }
    
    $Inst = new MyClass();
    echo $Inst->getSay();
    

提交回复
热议问题