2014-02-17 31 views
1

美好的一天!PHP包括主php類中的mysqli()類

我的php項目存在以下問題。我試圖在我的PHP主類中包含mysqli()類。這是我在PHP中使用OOP構建的第一個項目。

我有如下因素代碼:

<?php 
    class php{ 
    public function __construct($siteName,$sqlHost,$sqlUser,$sqlPass,$dbName){ 
     $this->info['SiteName']=$siteName; 
    } 
     //  vars 
    public $info=array(
        'SiteName'=>null, 
        'Author'=>'Costa V', 
        'Version'=>0, 
        'Build'=>0, 
        'LastUpdate'=>null); 
    private $sql=new mysqli($sqlHost,$sqlUser,$sqlPass,$dbName); 
     //  functions 
    } 
?> 

我也有一個main.php文件在那裏我發起這個類有:

<? 
error_reporting(E_ALL); 
$php=new php('Gerador de catalogo AVK','localhost','root','','avk_pdf_gen'); 
$pdf=new fpdf(); 
?> 

從哪裏獲得有關「新」的關鍵字錯誤在'$ sql'變量中。

另外我想問你給我的代碼評分,並給我提供任何與OOP相關的有用建議。

+2

您不能在編譯時實例化屬性,必須在運行時執行定義。這是你應該轉移到你的構造函數的東西。 (即整個私有$ sql = ...應該用一個簡單的私有$ sql代替;然後在你的__construct()函數中執行$ this-> sql = new mysqli – Tularis

+0

我給出的答案給了你信息你需要嗎?如果是這樣,請將其標記爲正確的。如果需要,還可以隨時提供更多問題作爲評論。 – Jite

回答

2

在構造函數中初始化變量通常是個好主意。
特別是當您嘗試初始化mysqli對象的變量在構造函數內部不存在於其他任何位置時。 Try:

class php { 
    private $sql; 
    public function __construct($siteName,$sqlHost,$sqlUser,$sqlPass,$dbName){ 
     // The parameters that are passed into the constructor when you do 'new php(..)' 
     // only exist within the constructor. 
     $this->info['SiteName']=$siteName; 
     $this->sql = new mysqli($sqlHost, $sqlUser, $sqlPass, $dbName); 
    } 
    // So if you are using the parameters passed into the constructor here 
    // (within the class declaration scope) 
    // They are not yet existing. 
}