What is the usage of php arrows?

青灯夜游
Release: 2023-02-26 21:12:02
Original
5318 people have browsed it

The "->" symbol in php is called the arrow operator. The left side of the arrow operator is to obtain the instance of the class, and the right side will specify and call the methods and attributes of the left class. In this article, we will Let’s introduce the usage of arrow operator in php.

What is the usage of php arrows?

Use the -> symbol to reference the properties and methods of a class. -> means calling

Syntax:

类 -> 类的成员变量或者成员函数
Copy after login

We use sample code below to illustrate the arrow operator in php.

The syntax defined is as follows.

class 类名{ 
    $属性名1 =“属性1”; 
    $属性名2 =“属性2”; 
    function 方法名1(){ 
        ... 处理过程... 
    } 
    function 方法名2(){ 
        ...处理过程 ... 
    } }
    }
Copy after login

Next is "instance", but this refers to an instance created from the defined class, which corresponds to the template above. If you specify the new operator and write it as classname(), an instance will be created.

In the following example, the generated instance is assigned to the variable $instance.

$instance = new 类名();
Copy after login

Arrow operator writing method

The arrow operator usage example is as follows.

The following code accesses "property name 1" and "property name 2"

$instance->属性名1;
$instance->属性名2;
Copy after login

The following code calls "method 1" and "method 2"

$instance->方法名1();
$instance->方法名2();
Copy after login

us Let’s look at a specific example

Let us use the arrow operator to explicitly specify the class name, attribute name, method name, processing in the method, and access each item in the above example sentence .

This time we define a Person class with its name as an attribute and introductionSelf as a method.

In addition, the __construct() that appears is a special method to be executed when using the new operator to create an instance.

// person类
class Person {
    // 名称
    $name;
    // 构造函数在实例生成的时的名称设置
    function__construct($name) {
        $this->name = $name;
    }
    // 进行自我介绍
    function introduceSelf() {
        echo "我是". $this->name ."同学".PHP_EOL;
    }
}
$taro = new Person("张三");
echo $taro->$name.PHP_EOL;
// 调用自我介绍方法
$taro->introduceSelf();
Copy after login

For more PHP related knowledge, please visit php中文网!

The above is the detailed content of What is the usage of php arrows?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template