我们在哪里使用 PHP 中的对象运算符“->”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3037526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:30:00  来源:igfitidea点击:

Where do we use the object operator "->" in PHP?

php

提问by nectar

What are the different ways where we can use object operators ->in PHP?

我们可以->在 PHP 中使用对象运算符的不同方式有哪些?

回答by Powerlord

PHP has two object operators.

PHP 有两个对象操作符。

The first, ->, is used when you want to call a method on an instance or access an instance property.

第一个 ,->用于在实例上调用方法或访问实例属性。

The second, ::, is used when you want to call a staticmethod, access a staticvariable, or call a parent class's version of a method within a child class.

::当您想要调用static方法、访问static变量或在子类中调用父类的方法版本时,使用第二个 , 。

回答by Mark Baker

When accessing a method or a property of an instantiated class

访问实例化类的方法或属性时

class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$a = new SimpleClass();
echo $a->var;
$a->displayVar();

回答by mmattax

Call a function:

调用函数:

$foo->bar();

Access a property:

访问属性:

$foo->bar = 'baz';

where $foois an instantiated object.

哪里$foo是一个实例化的对象。

回答by Wind Chimez

It is used when referring to the attributes of an instantiated object. e.g:

它在引用实例化对象的属性时使用。例如:

class a {
    public $yourVariable = 'Hello world!';
    public function returnString() {
        return $this->yourVariable;
    }
}

$object = new a();
echo $object->returnString();
exit();