Home >Backend Development >PHP Tutorial >Create a simple PHP object_PHP tutorial

Create a simple PHP object_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:32:54768browse

<?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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752581.htmlTechArticle?php// Define a Digimon class Digimon{var $name;var $hitPoint;var $attack ;var $defence;function attack() {echo "attack";}}// Create an object from class Digimon agu$agu = new Digimo...
Statement:
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