本文介绍了从类外部访问类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下课程:

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

然后我启动了一个类的实例:

I then started an instance of the class:

$Inst = new MyClass();

我现在如何在 MyClass 之外调用 $Say,例如,在文档上回显它?例如,有类似的东西:

How can I now call $Say outside MyClass hence, for example, echo it on the document? For example, having something like:

$Said = "He" . $Say

推荐答案

我强烈建议您通读 http://php.net/manual/en/language.oop5.php.它将教您 PHP 中 OOP 的基础知识.

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


在您的示例中, $Say 只是在 Talk() 范围内声明的另一个变量.它不是一个类属性.


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

使其成为类属性:

class MyClass {
    public $say = 'Something';

    public function Talk() {
        return $this->say;
    }
}

$inst = new MyClass();
$said = 'He ' . $inst->say;

然而,这违背了 Talk() 的目的.
最后一行应该是 $said = 'He '.$inst->Talk();

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

这篇关于从类外部访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 14:59