weixin_慕的地1468772
2021-01-14 01:11
<?php
date_default_timezone_set("PRC");
//类的定义以关键字class开始,后面跟着这个类的名称。类的命名通常每个单词的第一个字母大写。以中括号开始和结束
class Nbaplayer
{
public $name = "Jordan";
public $height = "198cm";
public $weight = "98kg";
public $team = "Bull";
public $playerNum = "23";
//构造函数,在对象被实例化的时候自动调用
function __construct($name,$height,$weight,$team,$playerNum)
{
echo "In Nbaplayer constructor"."\n";
$this->name =$name;
//$this是PHP里面的伪变量,表示对象自身。可以通过$this->的方式访问对象的属性和方法
$this->height =$height;
$this->weight =$weight;
$this->team = $team;
$this->playerNum =$playerNum;
}
//定义方法
public function run()
{
echo "Running\n";
}
public function jump()
{
echo "Jumping\n";
}
public function dribble()
{
echo "Dibbling\n";
}
public function shoot()
{
echo "Shooting\n";
}
public function dunk()
{
echo "Dunking\n";
}
public function pass()
{
echo "Passing\n";
}
}
//类到对象的实例化
//类的实例化为对象是使用关键字new,new之后紧跟类的名称和一对括号
$Jordan = new Nbaplayer("Jordan","198cm","98kg","Bull","23");
//对象中的属性成员可以通过->符号来访问
echo $Jordan -> name."\n";
$Jordan -> dribble()."\n";
$Jordan -> pass()."\n";
//每一次用new实例化对象的时候,都会用类名后面的参数列表调用构造函数
$Jordan = new Nbaplayer("James","203cm","120kg","Heat","6");
echo $James->name."\n";
?>
执行结果:
In Nbaplayer constructor | |
Jordan | |
Dibbling | |
Passing | |
In Nbaplayer constructor | |
最后一个实例化的对象没写对,问题发现了
最后一个echo
PHP面向对象编程
70153 学习 · 361 问题
相似问题