这篇文章主要为大家详细介绍了PHP利用面向对象的简单示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小玲来看看吧!
以前对面向对象仅限于死记硬背型,工作这么久了,回过头来看又是一翻体悟,供大家看看。
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 <$this->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);
本文来自:http://www.q1010.com/173/15698-0.html
注:关于PHP利用面向对象的简单示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。