OOP初探

/**************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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值