PHP面向?qū)ο笕筇攸c(diǎn)學(xué)習(xí)(充分理解抽象、封裝、繼承、多態(tài))
Jun 13, 2016 pm 12:00 PM
面象對(duì)向的三大特點(diǎn):封裝性、繼承性、多態(tài)性 首先簡(jiǎn)單理解一下抽象:
我們?cè)谇懊娑x一個(gè)類的時(shí)候,實(shí)際上就是把一類事物共有的屬性和行為提取出來(lái),形成一個(gè)物理模型(模版),這種研究問(wèn)題的方法稱為抽象
一、封裝性
封裝就是把抽取出來(lái)的數(shù)據(jù)和對(duì)數(shù)據(jù)的操作封裝在一起,數(shù)據(jù)被保護(hù)在內(nèi)部,程序的其他部分只有被授權(quán)的操作(方法)才能對(duì)數(shù)據(jù)進(jìn)行操作。
php提供了三種訪問(wèn)控制修飾符
public 表示全局,本類內(nèi)部,類外部,子類都可以訪問(wèn)
protected 表示受保護(hù)的,只有本類或子類可以訪問(wèn)
private 表示私有的,只有本類內(nèi)部可以訪問(wèn)
以上三種修飾符既可以修飾方法也可以修飾屬性(變量),方法如果沒(méi)有訪問(wèn)修飾符則默認(rèn)是public,成員屬性必須指定訪問(wèn)修飾符,在PHP4中也有這種寫法 var $name,表示公開屬性,不推薦這種寫法
例:
復(fù)制代碼 代碼如下:
class Person{
public $name;
protected $age;
private $salary;
function __construct($name,$age,$salary){
$this->name=$name;
$this->age=$age;
$this->salary=$salary;
}
public function showinfo(){
//這表示三個(gè)修飾符都可以在本類內(nèi)部使用
echo $this->name."||".$this->age."||".$this->salary;
}
}
$p1=new Person('張三',20,3000);
//這里屬于類外部,那么如果用下面的方法訪問(wèn)age和salary都會(huì)報(bào)錯(cuò)
// echo $p1->age; echo$p1->salary;
?>
那么現(xiàn)在就想在外部訪問(wèn)protected和private的元素和方法該怎么辦? 通常做法是通過(guò)public函數(shù)去訪問(wèn)這些變量 格式:
public function setxxxx($val){
$this->xxxx=$val;
}
public function getxxxx(){
return $this->xxxx;
}
這里帶set和get只是為了識(shí)別方便,并非必要
如:
public function getsalary(){
return $this->salary; //擴(kuò)展:這里可以調(diào)用一些方法,如判斷用戶名等,正確才給訪問(wèn)
}
在外部就可以通過(guò) echo $p1->getsalary();
如果要訪問(wèn) protected和private也可以使用以下方法,但不推薦使用,只要了解即可
__set() 和 __get()
__set()對(duì)protected或private屬性進(jìn)行賦值操作
__set($name,$val);
__get()獲取 protected 或 private的值
__get($name);
如:
復(fù)制代碼 代碼如下:
class testa{
protected $name;
//使用__set()來(lái)管理所有屬性
public function __set($pro_name,$pro_val){
//上面$pro_name和$pro_val可自定義
//下面$this->pro_name為既定,不可更改
$this->pro_name=$pro_val;
}
//使用__get()來(lái)獲取所有屬性值
public function __get($pro_name){
if(isset($pro_name)){
return $this->pro_name;
} else {
return null;
}
}
}
$n1=new testa();
//正常情況,類外部是不能訪問(wèn)protected屬性的,但是用了上面的方法就可以對(duì)它們進(jìn)行操作
$n1->name='小三';
echo $n1->name;
?>
//以上代碼看懂就行,不推薦使用
二、繼承性
先看一個(gè)例子:
復(fù)制代碼 代碼如下:
class Pupil{
public $name;
protected $age;
public function getinfo(){
echo $this->name.'||'.$this->age;
}
public function testing(){
echo 'this is pupil';
}
}
class Graduate{
public $name;
protected $age;
public function getinfo(){
echo $this->name.'||'.$this->age;
}
public function testing(){
echo 'this is Graduate';
}
}
?>
從上面的例子可以看出,當(dāng)多個(gè)類有很多共同屬性和方法時(shí),代碼的復(fù)用性不高,代碼冗余,思考css中的處理方法
解決方法 :繼承
復(fù)制代碼 代碼如下:
class Students{
public $name;
public $age;
public function __construct($name,$age){
$this->name=$name;
$this->age=$age;
}
public function showinfo(){
echo $this->name.'||'.$this->age;
}
}
class Pupil extends Students{
function testing(){
echo 'Pupil '.$this->name.' is testing';
}
}
class Graduate extends Students{
function testing(){
echo 'Graduate '.$this->name.' is testing';
}
}
$stu1=new Pupil('張三',20);
$stu1->showinfo();
echo '
';
$stu1->testing();
?>
從上面可以看出,繼承就是一個(gè)子類(Subclass)通過(guò) extends 父類 把父類(BaseClass)中的public 和 protected 的屬性和方法繼續(xù)下來(lái),不能繼承private屬性和方法
語(yǔ)法結(jié)構(gòu):
class 父類名{}
class 子類名 extends 父類名{}
細(xì)節(jié):
1、一個(gè)子類只能繼承一個(gè)父類(這里指直接繼承);如果希望繼承多個(gè)類的屬性和方法,可以使用多層繼承
例:
復(fù)制代碼 代碼如下:
class A{
public $name='AAA';
}
class B extends A{
public $age=30;
}
class C extends B{}
$p=new C();
echo $p->name;//這里會(huì)輸出AAA
?>
2、在創(chuàng)建某個(gè)子類對(duì)象時(shí),默認(rèn)情況下不會(huì)自動(dòng)調(diào)用其父類的構(gòu)造函數(shù)
例:
class A{
public function __construct(){
echo 'A';
}
}
class B extends A{
public function __construct(){
echo 'B';
}
}
$b=new B();//這里會(huì)優(yōu)先輸出B中的構(gòu)造方法,如果B中沒(méi)有構(gòu)造方法才會(huì)輸出A中的
3、在子類中如果需要訪問(wèn)父類的方法(構(gòu)造方法、成員方法 方法的修飾符為protected或private),那么可以使用 父類::方法名 或者 parent::方法名 來(lái)完成【這里parent和以前提到的self都均為小寫,大寫報(bào)錯(cuò)】
class A{
public function test(){
echo 'a_test';
}
}
class B extends A{
public function __construct(){
//兩種方法都行
A::test();
parent::test();
}
}
$b=new B();
5、如果一個(gè)子類(派生類)的方法與父類的方法完全一樣時(shí)(public,protected),我們稱為方法覆蓋或方法重寫(override),看下面的多態(tài)性
三、多態(tài)性
例 :
復(fù)制代碼 代碼如下:
class Animal{
public $name;
public $price;
function cry(){
echo 'i don\'t know';
}
}
class Dog extends Animal{
//覆蓋、重寫
function cry(){
echo 'Wang Wang!';
Animal::cry();//這里不會(huì)報(bào)錯(cuò),能正確執(zhí)行父類的cry();
}
}
$dog1=new Dog();
$dog1->cry();
?>
小結(jié):
1、當(dāng)一個(gè)父類知道所有的子類都有一個(gè)方法,但是父類不能確定該方法如何寫,可以讓子類去覆蓋它的方法,方法覆蓋(重寫),必須要求子類的方法名和參數(shù)個(gè)數(shù)完全一致
2、如果子類要去調(diào)用父類的某個(gè)方法(protected/public),可以使用 父類名::方法名 或者 parent::方法名
3、在實(shí)現(xiàn)方法重寫的時(shí)候,訪問(wèn)修飾符可以不一樣,但是子類方法的訪問(wèn)權(quán)限必須大于等于父類方法的訪問(wèn)權(quán)限(即不能縮小父類方法的訪問(wèn)權(quán)限)
如 父類public function cry(){} 子類 protected function cry(){} 則會(huì)報(bào)錯(cuò)
但是子類的訪問(wèn)權(quán)限可以放大,如:
父類private function cry(){} 子類 protected function cry(){} 可以正確執(zhí)行
擴(kuò)展:
方法重載(overload)
基本概念:函數(shù)名相同,但參數(shù)的個(gè)數(shù)或參數(shù)的類型不同,達(dá)到調(diào)用同一個(gè)函數(shù),可以區(qū)分不同的函數(shù)
在PHP5中雖然也支持重載,但是和其它語(yǔ)言還是有很大區(qū)別的,php中不能定義多個(gè)同名函數(shù)
PHP5中提供了強(qiáng)大的“魔術(shù)”函數(shù),使用這些魔術(shù)函數(shù),我們可以做到函數(shù)重載,
這里我們要到到 __call,當(dāng)一個(gè)對(duì)象調(diào)一個(gè)方法時(shí),而該方法不存在,則程序會(huì)自動(dòng)調(diào)用__call
【官方不推薦使用】
PHP中有以下幾個(gè)魔術(shù)常量:__LINE__ __FILE__ __DIR__ __FUNCTION__ __CLASS__ 等
例:
復(fù)制代碼 代碼如下:
class A{
function test1($p){
echo 'test1
';
}
function test2($p){
echo 'test2
';
}
function __call($method,$p){
//這里$p為數(shù)組,上面兩個(gè)變量名可自定義
if($method == 'test'){
if(count($p)==1){
$this->test1($p);
} else if(count($p)==2){
$this->test2($p);
}
}
}
}
$a=new A();
$a->test(5);
$a->test(3,5);
?>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w
