/**************by garcon1986******************/
面向对象的特点:继承(inheritance),多态(polymorphism),封装(encapsulation)
缺点:1. 小项目中需要更多的代码;2. 执行稍慢
类就是对象的蓝图/模板
Business logic 和 view logic 分离
类的方法用于操作他自己的数据(属性)
类中变量叫属性(variable=property),函数叫方法(function=method)
$this 是一个内置的变量,指向当前对象。可以用$this访问当前类的属性和调用方法
var等价于public
惯例(Convention):
<?php
class Something {
// In OOP classes are usually named starting with a cap letter.
var $x;
function setX($v) {
// Methods start in lowercase then use lowercase to separate
// words in the method name example getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>
代码:
class_lib.php:
<?php
error_reporting(E_ALL ^ E_NOTICE);
class person{
var $name;
public $height;
protected $social_insurance;
private $pinn_number;
function __construct($persons_name){
$this->name = $persons_name;
}
private function get_pinn_number(){
return $this->$pinn_number;
}
protected function set_name($new_name){
if(name != "Jimmy Two Guns"){
$this->name = strtoupper($new_name);
}
}
public function get_name(){
return $this->name;
}
}
class employee extends person{
function __construct($employee_name){
$this->set_name($employee_name);
}
protected function set_name($new_name){
if($new_name == "sun"){
$this->name = $new_name;
}
else{
parent::set_name($new_name);
}
}
}
?>
index.php:
<?php
include("class_lib.php");
$sun = new person("soleil");
$lei = new person("fleur");
echo "sun's fullname is: ".$sun->get_name()."<br />";
echo "lei's fullname is: ".$lei->get_name()."<br />";
$stephan = new person("steven");
echo "stephan's fullname is : ".$stephan->get_name()."<br />";
//Since $pinn_number was declared private, this line of code will generate an error.
//echo "private number is : ".$stephan->pinn_number."<br />";
$charles = new employee("charles");
echo $charles->get_name();
?>
参考:
http://www.killerphp.com/tutorials/object-oriented-php/index.php
http://www.killerphp.com/tutorials/object-oriented-php/downloads/oop_in_php_tutorial_for_killerphp.com.pdf
89

被折叠的 条评论
为什么被折叠?



