Calling steps: 1. Use the new keyword followed by a method with the same name as the class name to instantiate the class class into an object. The syntax is "variable name = new class name (parameter number list);" Or "$ variable name = new class name;"; 2. Use the special operator symbol "->" to call the member method in the object, the syntax is "$ variable name -> method name ();".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php calls the class class Method in
#Step 1: Instantiate the class class into an object
It is very easy to instantiate a class into an object, just use the new keyword And just add a method with the same name as the class name at the end. Of course, if you do not need to pass parameters for the object when instantiating the object, just use the class name directly after the new keyword without adding parentheses.
The instantiation format of the object is as follows:
$变量名 = new 类名(参数数列表); 或 $变量名 = new 类名;
The parameter description is as follows:
Variable name: the reference name of an object created through the class, The members of the object can be accessed through this name;
new: keyword, indicating that a new object is to be created;
Class name: Indicates the type of new object;
Parameter list: The constructor of the specified class is used to initialize the value of the object. If there is no constructor defined in the class, PHP will automatically create one without parameters. 's default constructor.
Step 2. Call the method in the object
The object contains member properties and member methods. Access the members and methods in the object. Accessing elements in an array is similar, members in an object can only be accessed through a reference to the object. But a special operator -> must be used to complete access to object members.
The syntax format for accessing member methods in an object is as follows:
$变量名 -> 成员方法名(); //访问对象中的成员方法
Example: Call the demo() method in the class class
<?php header('content-type:text/html;charset=utf-8'); class Website{ public function demo(){ echo '成员方法 demo()'; } } $student = new Website(); $student -> demo(); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to call methods in class in php. For more information, please follow other related articles on the PHP Chinese website!