2014-02-17 32 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. 
}