国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 PHP中實現(xiàn)面向?qū)ο缶幊蹋ㄉ希?/span>

PHP中實現(xiàn)面向?qū)ο缶幊蹋ㄉ希?/h1> Jun 21, 2016 am 09:15 AM
function obj php this


編程|對象

這篇文章介紹在PHP的面向?qū)ο缶幊蹋∣OP)。我將演示如何用面向?qū)ο蟮母拍罹幊鲚^少的代碼但更好的程序。祝大家好運。

  面向?qū)ο缶幊痰母拍顚γ恳粋€作者來說都有不同的看法,我提醒一下一個面向?qū)ο笳Z言應有的東西:

   - 數(shù)據(jù)抽象和信息隱藏
   - 繼承
   - 多態(tài)性

  在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 seprate
// words in the method name example getValueOfArea()
$this->x=$v;
}

function getX() {
return $this->x;
}
}

?>
  當然你可以用你自己的辦法,但有一個標準總是好的。

  PHP中類的數(shù)據(jù)成員使用 "var" 定義,數(shù)據(jù)成員是沒有類型直到被賦值。一個數(shù)據(jù)成員可能是一個 integer、數(shù)組、聯(lián)合數(shù)組(associative array)或甚至對象(object). 方法在類里定義成函數(shù),在方法里存取數(shù)據(jù)成員,你必須使用$this->name 這樣的辦法,否則對方法來說是一個函數(shù)的局部變量。

  使用 new 來創(chuàng)建一個對象

$obj = new Something;
  然后使用成員函數(shù)

$obj->setX(5);
$see = $obj->getX();
  setX 成員函數(shù)將 5 賦給對象(而不是類)obj 中成員變量, 然后 getX 返回值 5.

  你也可以用對象引用來存取成員變量,例如:$obj->x=6; 然而,這不一種好的面向?qū)ο缶幊痰姆椒āN覉猿帜銘褂贸蓡T函數(shù)來設(shè)置成員變量的值和通過成員函數(shù)來讀取成員變量。如果你認為成員變量是不可存取的除了使用成員函數(shù)的辦法,你將成為一個好的面向?qū)ο蟪绦騿T。 但不幸的是PHP本身沒有辦法聲明一個變量是私有的,所以允許糟糕的代碼存在。

  在 PHP 中繼承使用 extend 來聲明。

class Another extends Something {
 var $y;
 function setY($v) {
  // Methods start in lowercase then use lowercase to seperate
  // words in the method name example getValueOfArea()
  $this->y=$v;
 }

 function getY() {
  return $this->y;
 }
}

?>
  這樣類 "Another" 的對象擁有父類的所用成員變量及方法函數(shù),再加上自己的成員變量及成員函數(shù)。如:

$obj2=new Another;
$obj2->setX(6);
$obj2->setY(7);
  多重繼承不被支持,所以你不能讓一個類繼承多個類。

  在繼承類中你可以重新定義來重定義方法,如果我們在 "Another" 重新定義 getX,那么我們不再能存取 "Something" 中的成員函數(shù) getX. 同樣,如果我們在繼承類中聲明一個和父類同名的成員變量,那么繼承類的變量將隱藏父類的同名變量。

  你可以定義一個類的構(gòu)造函數(shù), 構(gòu)造函數(shù)是和類同名的成員函數(shù),在你創(chuàng)建類的對象時被調(diào)用。

class Something {
 var $x;

 function Something($y) {
  $this->x=$y;
 }

 function setX($v) {
  $this->x=$v;
 }

 function getX() {
  return $this->x;
 }
}

?>
  所以可以用如下方法創(chuàng)建對象:

$obj=new Something(6);
  構(gòu)造函數(shù)自動賦值 5 給成員變量 x, 構(gòu)造函數(shù)和成員函數(shù)都是普通的PHP函數(shù),所以你可以使用缺省參數(shù)。

function Something($x="3",$y="5")
  然后:

$obj=new Something(); // x=3 and y=5
$obj=new Something(8); // x=8 and y=5
$obj=new Something(8,9); // x=8 and y=9
  缺省參數(shù)的定義方法和 C++ 一樣,因此你不能傳一個值給 Y 但讓 X 取缺省值,實參的傳遞是從左到右,當沒有更多的實參時函數(shù)將使用缺省參數(shù)。

  只有當繼承類的構(gòu)造函數(shù)被調(diào)用后,繼承類的對象才被創(chuàng)建,父類的構(gòu)造函數(shù)沒有被調(diào)用,這是PHP不同其他面向?qū)ο笳Z言的特點,因為構(gòu)造函數(shù)調(diào)用鏈是面向?qū)ο缶幊痰奶攸c。如果你想調(diào)用基類的構(gòu)造函數(shù),你不得不在繼承類的構(gòu)造函數(shù)中顯式調(diào)用它。這樣它能工作是因為在繼承類中父類的方法全部可用。

function Another() {
$this->y=5;
$this->Something(); //explicit call to base class constructor.
}

?>
  在面向?qū)ο缶幊讨幸环N好的機制是使用抽象類,抽象類是一種不能實例化而是用來給繼承類定義界面的類。設(shè)計師經(jīng)常使用抽象類來強制程序員只能從特定的基類來繼承,所以就能確定新類有所需的功能,但在PHP中沒有標準的辦法做到這一點,不過:

  如果你在定義基類是需要這個特點,可以通過在構(gòu)造函數(shù)中調(diào)用 "die",這樣你就可以確保它不能實例化,現(xiàn)在定義抽象類的函數(shù)并在每個函數(shù)中調(diào)用 "die",如果在繼承類中程序員不想重定義而直接調(diào)用基類的函數(shù),將會產(chǎn)生一個錯誤。

  此外,你需要確信因為PHP沒有類型,有些對象是從基類繼承而來的繼承類創(chuàng)建的,因此增加一個方法在基類來辨別類(返回 "一些標識")并驗證這一點,當你收到一個對象作為參數(shù)派上用場。 但對于一個惡棍程序沒用辦法,因為他可以在繼承類中重定義此函數(shù),通常這種辦法只對懶惰的程序員奏效。當然,最好的辦法是防止程序接觸到基類的代碼只提供界面。

  重載在PHP中不被支持。在面向?qū)ο缶幊讨心憧梢酝ㄟ^定義不同參數(shù)種類和多少來重載一個同名成員函數(shù)。PHP是一種松散的類型語言,所以參數(shù)類型重載是沒有用的,同樣參數(shù)個數(shù)不同的辦法重載也不能工作。

  有時候,在面向?qū)ο缶幊讨兄剌d構(gòu)造函數(shù)很有用,所以你能以不同的方式創(chuàng)建不同的對象(通過傳遞不同的參數(shù)個數(shù))。一個小巧門可以做到這一點:

class Myclass {
function Myclass() {
$name="Myclass".func_num_args();
$this->$name();
//Note that $this->$name() is usually wrong but here
//$name is a string with the name of the method to call.
}

function Myclass1($x) {
code;
}
function Myclass2($x,$y) {
code;
}
}

?>
  通過這種辦法可以部分達到重載的目的。

$obj1=new Myclass(1); //Will call Myclass1
$obj2=new Myclass(1,2); //Will call Myclass2
  感覺還不錯!



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

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

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A Simple Guide to PHP Setup A Simple Guide to PHP Setup Jul 18, 2025 am 04:25 AM

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

Writing Effective PHP Comments Writing Effective PHP Comments Jul 18, 2025 am 04:44 AM

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Mastering PHP Block Comments Mastering PHP Block Comments Jul 18, 2025 am 04:35 AM

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

Improving Readability with Comments Improving Readability with Comments Jul 18, 2025 am 04:46 AM

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

See all articles