本文目錄一覽:
php中面向對象編程是什麼意思,到底用在什麼地方,用一個項目中的實際例子來舉例說明
可以這樣理解,
1、類是模具,對象是模具生成的產品,就是印刷術一樣,有了一個字一個字的模子,要印出一個字來就方便了,想印就印,你可以印,我也可以印。
2、在PHP中怎麼做一個模具出來呢,就用 class申明,它就表示你要造一個模具了,但這個模具是做什麼用的,就要在裏面添加函數來表達了,函數名就是這個類的方法名,函數完成的功能就是類的方法。當然函數要實現功能代碼中肯定要用到變量,這個就是所謂的類的成員以或者說成是類的屬性。
3、有了類的屬性有了類的方法,這就完成了一個類的定義,也就是模具做好了,接下來要理解的就是,怎樣去用這個類了。就好像是要看一本書你不可能到印刷廠去把字的模具拿來拼成一頁一頁書來看吧,肯定是在紙上印刷出來。這個印刷的過程就是對象生成的過程也叫類的實例化。PHP中用new關鍵字來生成對象。比如前面定義的類名為 牛,這個牛有一個方法(函數)是:耕地。當然耕地這個函數,要怎樣去實現那是另外要的事情了。現在要說的是怎麼用牛的耕地方法,首先實例化,在PHP中這樣表示:牛1= new 牛。這樣 牛這個類 就有了一個具體可以使喚的牛1了 要想用牛1的耕地方法,意思就是「調用類(對象)的方法」,PHP中這樣表示,牛1-耕地;如果你想要100頭牛,就new100個出來就行,而不用每當要用牛的時候都去寫牛的代碼和牛耕地的代碼了。
4、上面說的是一個理解過程,要實現就要用到具體的PHP的語法了,比如怎樣申明變量 ,怎樣賦值,怎樣用運算符來運算,怎樣寫循環結構,怎樣寫選擇結構,等等 。
php怎樣用面向對象的方法將表單值插入數據庫?那個方法要怎麼寫?
一個簡單的例子
?php
include ‘db_content.php’; //數據庫連接
class db
{
public function insert($username)
{
$sql = “insert into user (id,username) values (null, $username)”;
mysql_query($sql);
}
}
if (isset($_POST[‘sub’]))
{
$db = new db();
$db-insert($_POST[‘username’]);
}
?
form action=”” method=”post”
input type=”text” name=”username” value=””
input type=”submit” name=”sub” value=”提交”
/form
面向對象設計的PHP面向對象實例
class MySql {
var $user,$pass,$host,$db;
var $id,$data,$fields,$row,$row_num,$insertid,$version,$query_num=0;
function __construct($host,$user,$pass,$db)
{
$this-host = $host;
$this-pass = $pass;
$this-user = $user;
$this-db = $db;
$this-dbconnect($this-host, $this-user, $this-pass);
$this-selectdb($this-db);
if($this-version() ‘4.1’)
mysql_query(SET NAMES utf8);
}
function dbconnect($host,$user,$pass)
{
$this-id = @ mysql_connect($host,$user,$pass) OR
sysMsg(連接數據庫失敗,可能是mysql數據庫用戶名或密碼錯誤);
}
function selectdb($db)
{
@ mysql_select_db($db,$this-id) OR die(未找到指定數據庫);
}
function query($sql)
{
$query = @ mysql_query($sql,$this-id) OR die(SQL語句執行錯誤:$sql br /.$this-geterror());
$this-query_num();
return $query;
}
function fetch_array($query)
{
$this-data = @mysql_fetch_array($query);
return $this-data;
}
function query_num()
{
$this-query_num++;
}
function num_fields($query)
{
$this-fields = @mysql_num_fields($query);
return $this-fields;
}
function fetch_row($query)
{
$this-row = @mysql_fetch_row($query);
return $this-row;
}
function num_rows($query)
{
$this-row_num = @mysql_num_rows($query);
return $this-row_num;
}
function insert_id()
{
$this-insertid = mysql_insert_id();
return $this-insertid;
}
function version()
{
$this-version = mysql_get_server_info();
return $this-version;
}
function fetch_one_array($sql)
{
$query = $this-query($sql);
$this-data = $this-fetch_array($query);
return $this-data;
}
function geterror()
{
return mysql_error();
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/295687.html