以前对面向对象仅限于死记硬背型,工作这么久了,回过头来看又是一翻体悟,供大家看看。
1.final
final:php5新增一个final关键字。如果父类中的方法被声明为final,则子类无法覆盖该方法;如果一个类被声明final,则不能被继承。
复制代码 代码如下:
class BaseClass{
public function test(){
ehco "test";
}
final public function moreTest(){
echo "moretest";
}
}
class ChildClass extends BaseClass{
public function moreTest(){
echo "moretest";
}
}
// 产生 Fatal error: Cannot override final method BaseClass::moretest()
复制代码 代码如下:
class Person{
protected $name;
protected $email;
public function setName($name){
$this->name = $name;
}
public function setEmail($email){
$this->email = $email;
}
public function __toString(){
return "$this->name email>";
}
}
$rasums = new Person;
$rasums->setName('test');
$rasums->setEmail('test@qq.com');
print $rasums;
复制代码 代码如下:
interface ChildTest{
public function childTest();
}
class FathTest implements ChildTest1,ChildTest2{
public function childTest(){
echo 1;
}
…………
}
复制代码 代码如下:
abstract class Database{
abstract public function connect();
abstract public function query();
abstract public function fetch();
abstract public function close();
}
复制代码 代码如下:
class Address{
protected $city;
protected $country;
public function setCity($city){$this->city = $city;}
public function getCity(){return $this->city;}
public function setCountry($country){$this->country = $country;}
public function getCountry(){return $this->country;}
}
class Person{
protected $name;
protected $address;
//浅克隆
public function __construct(){
$this->address = new Address;
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function __call($method,$arguments){
if(method_exists($this->address,$method)){
return call_user_func_array(array($this->address,$method),$arguments);
}
}
//深克隆
public function __clone(){
$this->address = clone $this->address;
}
}
$test1 = new Person;
$test2 = clone $test1;
$test1->setName('testname1');
$test1->setCity('testcity1');
$test2->setName('testname2');
$test2->setCity('testcity2');
echo $test1->getName().'-'.$test1->getCity()."\n";
echo $test2->getName().'-'.$test2->getCity()."\n";
//testname1-testcity2
//testname2-testcity2
复制代码 代码如下:
class Person{
protected $__data = array('email','test');
public function __get($property){
if(isset($this->__data[$property])){
return $this->__data[$property];
}else{
return false;
}
}
public function __set($property,$value){
if(isset($this->__data[$property])){
return $this->__data[$property] = $value;
}else{
return false;
}
}
public function __isset($property){
if(isset($this->__data[$property])){
return true;
}else{
return false;
}
}
public function __unset($property){
if(isset($this->__data[$property])){
return unset($this->__data[$property]);
}else{
return false;
}
}
}
$test = new Person;
$test->email= 'test';
var_dump($test->email);