PHP 中的对象运算符

Sheeraz Gul 2023年1月30日
  1. 在 PHP 中使用对象运算符访问对象的成员
  2. 在 PHP 中使用对象运算符访问类的属性
PHP 中的对象运算符

对象运算符 (->) 用于 PHP 中的面向对象编程。它用于实例化一个类或可用于访问 PHP 中的任何对象。

本教程将演示如何在 PHP 中使用对象运算符。

在 PHP 中使用对象运算符访问对象的成员

在下面的示例中,我们创建一个类,然后实例化它以使用对象运算符 (->) 访问所提供对象的成员。

例子:

<?php
$demo_obj = (object) array('1' => 'John','2' => 'Shawn','3' => 'Michelle');
echo $demo_obj->{'1'}."<br>";
echo $demo_obj->{'2'}."<br>";
echo $demo_obj->{'3'};
?>

输出:

John
Shawn
Michelle

在 PHP 中使用对象运算符访问类的属性

对象运算符 (->) 也用于访问类的属性。下面的代码创建了一个具有两个变量和一个方法的类。

例子:

<?php
class Demo_Class {
	public $demo;
    public $demo1 = "This is delftstack";

    public function Demo_Method() {
    echo "This is delftstack from demo method.";
    }
}
$demoinstance = new Demo_Class();

$demoinstance->demo="delftstack"; // Assign "delftstack" to "demo" variable
echo $demoinstance->demo;
echo "<br>";
echo $demoinstance->demo1; //print demo 1
echo "<br>";
$demoinstance->Demo_Method(); // Run "Demo_Method()"
?>

输出:

delftstack
This is delftstack
This is delftstack from demo method.

对象运算符 (->) 也可用于为变量赋值和调用方法。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - PHP Object