一篇入門的 Class 文章
Jun 21, 2016 am 09:11 AM剛在大略瀏覽了一下首頁更新的那篇有關(guān)Class的文章(指PHPE的那篇 http://www.phpe.net/articles/389.shtml ),很不錯,建議看看。
對類的摸索~~俺用了半年時間才大概理解類的作用和實現(xiàn)。主要是沒有一篇能讓我理解的文章(之前沒接觸過任何OO的東西)。
以我的觀點來說說PHP中的Class,用于表達的語言都是非正式的語言,也不能確定是否正確。
建立一個類很簡單。
PHP代碼:--------------------------------------------------------------------------------
class my_class {}
--------------------------------------------------------------------------------
類到底干什么呢?很多人都是什么黑匣子,我在這里稱它為一個獨立的整體。我們只知道類名,而不知道里面有什么東西。那么,該如何使用這個類呢?
首先:要知道它里面是否定義了公共的變量--專業(yè)術(shù)語上稱它為“屬性”。
其次:要知道它里面定義了什么函數(shù)--專業(yè)術(shù)語中稱它為“方法”。
我都被這些專業(yè)術(shù)語搞糊涂了,所以干脆不理它了。
類中的如何定義公共變量,它有什么作用呢?
很簡單,我們來擴充 my_class 類
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username;
}
--------------------------------------------------------------------------------
看上面很簡單,我們定義了一個公共的變量,只是用 var+空格+普通變量名 構(gòu)成。它有什么用呢?考慮一下函數(shù)中,如果我們要訪問函數(shù)外的變量,是不是要先 global 一下呢?這個想實現(xiàn)的效果也是如此,它是想讓這個類中的所有函數(shù)都能訪問它,而它區(qū)別于函數(shù)的一個地方,是類的外部也可以訪問這個變量,我隨后再講外部如何訪問它。還有一個區(qū)別,不能用復雜的語句給這個變量賦值(具體的等理解了類以后自己去看規(guī)則)。給它一個默認值
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username = "深空";
}
--------------------------------------------------------------------------------
OK,定義了一個公共的變量了,接下來定義一個函數(shù)(也就是所謂的“方法”)。
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username = "深空";
function show_username()
{
}
}
--------------------------------------------------------------------------------
這個定義函數(shù)跟普通的定義函數(shù)形式上沒什么區(qū)別了。簡單就好,定義一個打印 $username 的函數(shù):
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username = "深空";
function show_username($username)
{
echo $username;
}
}
--------------------------------------------------------------------------------
到這里可能某些人開始迷糊了,呵呵,最關(guān)鍵的就是這里了,看清楚了?,F(xiàn)在有三個 $username 了。到底哪個是哪個啊~~
函數(shù)所帶的行參,不用解釋了吧?這個函數(shù)功能就是打印行參所接收的值,也就是如果:
PHP代碼:--------------------------------------------------------------------------------
show_username("豬頭深空");
--------------------------------------------------------------------------------
那么它將打印 “豬頭深空” ,就這么簡單。
怎么樣訪問這個函數(shù)?肯定不是我上面說的那樣直接 show_username("豬頭深空"); 了,別急,類有類的一套。如下:
PHP代碼:--------------------------------------------------------------------------------
$Name = new my_class();
--------------------------------------------------------------------------------
這樣就初始化上面的那個 my_class 的類了,并把這個對象賦給變量 $Name ,你可以這樣理解,這個變量就代表整個類了,呵呵。
使用類中的函數(shù):
PHP代碼:--------------------------------------------------------------------------------
$Name->show_username("豬頭深空");
--------------------------------------------------------------------------------
暈了,為什么這么復雜?還要箭頭?其實很形象的。本來已經(jīng)把類給了變量 $Name 了是吧?也就是 $Name 代表了這個類,然后用一個箭頭指向類中的 show_username 這個函數(shù)。就是這么簡單,也就是說,這個函數(shù)是這個類中的,而不是其他的函數(shù)--你就理解為表示一個區(qū)別吧,呵呵。
試試看哦,打印出 “豬頭深空” 這四個字了。你說為什么要這么復雜?用函數(shù)不是也能實現(xiàn)么?我說,這么簡單的你當然看不出好處了,我們繼續(xù)擴充。
還有一個疑問:剛才說的“公共的變量”怎么一點用處都沒有呢?為什么這個函數(shù)不會自動接收這個公共變量 var $username 中的默認值?也就是如果我使用:
PHP代碼:--------------------------------------------------------------------------------
$Name->show_username($username);
--------------------------------------------------------------------------------
會有什么結(jié)果呢?答案是沒有任何輸出。因為你沒有給形參 $username 一個值。
那么該怎么使用這個公共的變量?我們來修改一下這個類:
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username = "深空";
function show_username()
{
echo $this->username;
}
}
--------------------------------------------------------------------------------
哇靠,不是吧,這回臉形參都沒有了?還多了一個$this->,暈了不是,呵呵。其實這也是類的一個最大的方便之處。
$this 的作用:訪問一個公共的變量,或者類里面的函數(shù)。
訪問?這么專業(yè)?其實就是用 $this->username 來代替 var $username 而已拉,$this 用來說明它是公共的??梢栽L問的,函數(shù)外部的東西。
試試看:
PHP代碼:--------------------------------------------------------------------------------
$Name->show_username();
--------------------------------------------------------------------------------
看到了吧,終于打印 “深空” 這兩個字了,娃哈哈。
我不打印“深空”這兩個字,我要打印“豬頭深空”,怎么辦?很簡單,我們給這個公共變量重新賦值拉。服了你了。
PHP代碼:--------------------------------------------------------------------------------
$Name->username = "豬頭深空";
--------------------------------------------------------------------------------
這個能明白意思么?$Name->username 表示的是類里面的這個公共變量。等號賦值不用我解釋了。
我們再來打印看看
PHP代碼:--------------------------------------------------------------------------------
$Name->show_username();
--------------------------------------------------------------------------------
哈哈,終于打印“豬頭深空”了。不錯吧,很方便吧,不用形參也能任意修改打印值哦~~。
不過單單打印一個名稱也太沒意思了,我們說點歡迎的話吧,來擴充一下這個類,創(chuàng)建一個名叫 Welcome 的函數(shù):
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username = "深空";
function show_username()
{
echo $this->username;
}
function Welcome()
{
}
}
--------------------------------------------------------------------------------
恩,實現(xiàn)什么功能好呢?簡單點吧,就實現(xiàn)在名字前面有 “歡迎” 兩個字好了
PHP代碼:--------------------------------------------------------------------------------
class my_class
{
var $username = "深空";
function show_username()
{
echo $this->username;
}
function Welcome()
{
echo "歡迎";
$this->show_username();
}
}
--------------------------------------------------------------------------------
第二次看到 $this 了吧?$this->show_username(); 干什么用呢?其實它就是調(diào)用 show_username 這個函數(shù),用 $this 來表示這個函數(shù)在類中并且和 Welcome 函數(shù)平行,而不是在其他地方(比如Welcome函數(shù)中)。
Welcome 函數(shù)實現(xiàn)的功能很簡單,首先打印兩個字"歡迎",然后接下去執(zhí)行 show_username 函數(shù),打印名字。
來試試這個函數(shù)吧:
PHP代碼:--------------------------------------------------------------------------------
$Name->Welcome();
--------------------------------------------------------------------------------
看到了吧,打印出“歡迎深空”這四個字了。
可是我要打印“歡迎豬頭深空”,怎么辦?我服了你了,我們給公共變量 var $username 一個值吧:
PHP代碼:--------------------------------------------------------------------------------
$Name->username = "豬頭深空";
--------------------------------------------------------------------------------
接下去打印歡迎語:
PHP代碼:--------------------------------------------------------------------------------
$Name->Welcome();
--------------------------------------------------------------------------------
嘿嘿,終于打印“歡迎豬頭深空”了。
怎么樣?明白了類的用法了么?好處在于能夠調(diào)用類中的任意函數(shù),只要用 $this 指出來,可以改變一個公共變量的值,可以在類中的函數(shù)中使用這個公共變量。………多了去了,它的應用等待你去發(fā)現(xiàn)了。

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

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
