您的位置:首页 > 编程语言 > PHP开发

php 简单对象的创建

2014-11-23 00:00 393 查看
摘要: php

<?php

/**
*  对象的定义
*
*/
class Student{

public   $PI=3.141592653;
//常量定义不加$
const C ="LOVE";
private $name ;
private $age ;

//构造方法
public function __construct($name,$age){
$this->age=$age;
$this->name=$name;
}
//析构方法 销毁对象 释放内存
public function __destruct(){
echo '<h2 style="color:red;">对象被销毁,调用析构方法!</h2>';
}
public function getName (){
return $this->name;
}

public function setName($name){
$this->name = $name;
}

public function setAge($age){
/**
* 对象->方法名
* 方法名或者变量前不加 $
*/
$this->age=$age;
}
public function getAge(){
return $this->age;
}

}
//实例化
$student = new Student();
$age = 23;
$name = "万年青";
//为对象的参数赋值
$student->setAge($age);
$student->setName($name);
echo $student->getAge().'<br>';
echo $student->getName().'<br>';
echo $student->PI.'<br>';
// :: 引用常量
echo Student::C .'<br>';

$s2 =new Student("php", 5);
echo '构造方法:'.$s2->getAge();

结果如下图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: