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

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

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


編程|對(duì)象

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

  面向?qū)ο缶幊痰母拍顚?duì)每一個(gè)作者來說都有不同的看法,我提醒一下一個(gè)面向?qū)ο笳Z言應(yīng)有的東西:

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

  在PHP中使用類進(jìn)行封裝的辦法:

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;
}
}

?>
  當(dāng)然你可以用你自己的辦法,但有一個(gè)標(biāo)準(zhǔn)總是好的。

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

  使用 new 來創(chuàng)建一個(gè)對(duì)象

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

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

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

  在 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" 的對(duì)象擁有父類的所用成員變量及方法函數(shù),再加上自己的成員變量及成員函數(shù)。如:

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

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

  你可以定義一個(gè)類的構(gòu)造函數(shù), 構(gòu)造函數(shù)是和類同名的成員函數(shù),在你創(chuàng)建類的對(duì)象時(shí)被調(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)建對(duì)象:

$obj=new Something(6);
  構(gòu)造函數(shù)自動(dòng)賦值 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++ 一樣,因此你不能傳一個(gè)值給 Y 但讓 X 取缺省值,實(shí)參的傳遞是從左到右,當(dāng)沒有更多的實(shí)參時(shí)函數(shù)將使用缺省參數(shù)。

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

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

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

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

  此外,你需要確信因?yàn)镻HP沒有類型,有些對(duì)象是從基類繼承而來的繼承類創(chuàng)建的,因此增加一個(gè)方法在基類來辨別類(返回 "一些標(biāo)識(shí)")并驗(yàn)證這一點(diǎn),當(dāng)你收到一個(gè)對(duì)象作為參數(shù)派上用場。 但對(duì)于一個(gè)惡棍程序沒用辦法,因?yàn)樗梢栽诶^承類中重定義此函數(shù),通常這種辦法只對(duì)懶惰的程序員奏效。當(dāng)然,最好的辦法是防止程序接觸到基類的代碼只提供界面。

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

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

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;
}
}

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

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



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 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)

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

See all articles