酷!學園
2010-03-10 19:25 *
歡迎光臨, 訪客. 請先 登入註冊一個帳號.
您忘了 啟用您的帳號嗎?

請輸入帳號, 密碼以及預計登入時間
新聞:
強烈建議,新手請先閱讀:致提問者的一些建議再致提問者
 
   首頁 | Study-Area | 鳥園 | 鳥哥的Linux私房菜   說明 搜尋 日曆 登入 註冊  
頁: [1]
  列印  
作者 主題: 關於__construct的問題  (閱讀 596 次)
0 會員 以及 1 訪客 正在閱讀本篇主題.
wing5217
懷疑的國中生
**
文章: 42


檢視個人資料
« 於: 2010-01-27 19:20 »

各位學長

看了一個例子是建立資料庫連線的類別
程式碼:
class mysql{
var $host = 'localhost';
var $name = 'root';
var $pwd = 'root';
var $Base = 'db';

                     function __construct($host='',$name='',$pwd='',$Base=''){
   if($host != '')
       $this->host = $host;
   if($name != '')
       $this->name = $name;
   if($pwd != '')
                     $this->pwd = $pwd;
   if($Base != '')
       $this->Base = $dBase;
}
}
想請問 __construct($host='',$name='',$pwd='',$Base=''){


$host,$name,$pwd,$Base

參數的值是那邊來的

if($host != '')  是指var $host = 'localhost';裡的值嗎?

可以這樣子寫嗎?

不過我不了解的是 既然它已經有給成員變數初值了

為什麼還要加 __construct初始化

$this->host = $host; 把已經有的值又設定下去一次

小弟看的書對初始化__construct使用參數的方法

是在建立物件時使用

就是在建立物件時 設定參數初值

$connect = new mysql('localhost','root','root','db');

function __construct($host,$name,$pwd,$Base){

  if($host != '')
      $this->host = $host;
   .
   .
   .
}
不太了解 第一個例子為什麼要那樣寫

謝謝回答
« 最後編輯時間: 2010-01-27 19:34 由 wing5217 » 已記錄
yamaka
俺是博士!
*****
文章: 3884


檢視個人資料 個人網站
« 回覆文章 #1 於: 2010-01-27 19:37 »

各位學長

看了一個例子是建立資料庫連線的類別
程式碼:
class mysql{
var $host = 'localhost';
var $name = 'root';
var $pwd = 'root';
var $Base = 'db';

                     function __construct($host='',$name='',$pwd='',$Base=''){
   if($host != '')
       $this->host = $host;
   if($name != '')
       $this->name = $name;
   if($pwd != '')
                     $this->pwd = $pwd;
   if($Base != '')
       $this->Base = $dBase;
}
}
想請問 __construct($host='',$name='',$pwd='',$Base=''){


$host,$name,$pwd,$Base

參數的值是那邊來的

if($host != '')  是直接指var $host = 'localhost';裡的值嗎?

可以這樣子寫嗎?

不過我不了解的是 既然它已經有給成員變數初值了

為什麼還要加 __construct初始化

小弟看的書對初始化__construct使用參數的方法

是在建立物件時使用

就是在建立物件時 設定參數初值

$connect = new mysql('localhost','root','root','db');

function __construct($host,$name,$pwd,$Base){

  if($host != '')
      $this->host = $host;
   .
   .
   .
}
不太了解 第一個例子為什麼要那樣寫

謝謝回答

存取 class 自己內部的 property 或 method 要用 $this->
所以那個 $host 還有其他3個都是指傳入的變數

http://tw.php.net/manual/en/language.oop5.basic.php

官網的說明, 建議好好看一看
已記錄
wing5217
懷疑的國中生
**
文章: 42


檢視個人資料
« 回覆文章 #2 於: 2010-01-27 19:47 »

學長 所以它的意思是 可以在建立物件時 用參數順便更改$host,$name,$pwd,$Base這些變數的值

如果沒有 就以原來賦值為準 這樣子嗎?
已記錄
yamaka
俺是博士!
*****
文章: 3884


檢視個人資料 個人網站
« 回覆文章 #3 於: 2010-01-27 19:52 »

對, 這是很基本的用法
不要把這些資料寫死
在應用上會比較方便
如果要使用預設設定
就可以直接用

new mysql()
已記錄
wing5217
懷疑的國中生
**
文章: 42


檢視個人資料
« 回覆文章 #4 於: 2010-01-27 19:54 »

這樣我了解了 感謝
已記錄
頁: [1]
  列印  
 
前往:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
本頁花了 0.071 秒,以及 16 次的資料庫查詢。