Access class property from outside of class

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

    I strongly recommend you read through http://php.net/manual/en/language.oop5.php. It will teach you the fundamentals of OOP in PHP.


    In your example, $Say is just another variable declared within Talk()'s scope. It is not a class property.

    To make it a class property:

    class MyClass {
        public $say = 'Something';
    
        public function Talk() {
            return $this->say;
        }
    }
    
    $inst = new MyClass();
    $said = 'He ' . $inst->say;
    

    That defeats the purpose of Talk() however.
    The last line ought to be $said = 'He '. $inst->Talk();

提交回复
热议问题