What are the different ways where we can use object operators ->
in PHP?
我们可以在PHP中使用对象运算符的不同方法是什么?
4 个解决方案
#1
79
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 static
method, access a static
variable, or call a parent class's version of a method within a child class.
第二个::,用于在子类中调用静态方法,访问静态变量或调用父类的方法版本时使用。
#2
18
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();
#3
8
Call a function:
调用函数:
$foo->bar();
Access a property:
访问一个属性:
$foo->bar = 'baz';
where $foo
is an instantiated object.
其中$ foo是一个实例化对象。
#4
4
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();
#1
79
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 static
method, access a static
variable, or call a parent class's version of a method within a child class.
第二个::,用于在子类中调用静态方法,访问静态变量或调用父类的方法版本时使用。
#2
18
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();
#3
8
Call a function:
调用函数:
$foo->bar();
Access a property:
访问一个属性:
$foo->bar = 'baz';
where $foo
is an instantiated object.
其中$ foo是一个实例化对象。
#4
4
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();