Home >Backend Development >PHP Tutorial >Create a simple PHP object_PHP tutorial
<?php // 定义一个数码暴龙类 class Digimon{ var $name; var $hitPoint; var $attack; var $defence; function attack() { echo "attack"; } } // 从类Digimon创建对象agu $agu = new Digimon(); // 给对象agu赋值 $agu -> name = "亚古兽"; $agu -> hitPoint = 50; $agu -> attack = "12"; $agu -> defence = "18"; // 访问对象agu的字段 echo $agu -> name."的生命值为".$agu -> hitPoint."<br>"; echo $agu -> name."的攻击力为".$agu -> attack."<br>"; echo $agu -> name."的防御力为".$agu -> defence."<br>"; // 访问对象agu的方法 echo $agu -> name."目前动作为"; echo $agu -> attack(); ?>
Program output:
Agumon's HP is 50
Agumon's attack power is 12
Agumon's defense power is 18
Agumon's current action is attack
In the code, how to create a class, how to create an object from a class, how to access the fields of the object, and how to access the methods of the object are all clearly demonstrated.
PHP’s OOP programming is similar to Java’s. If you have a foundation in Java programming, PHP’s OOP programming is quite easy to get started.