如何在另一个类中使用类中的变量

时间:2014-04-04 12:08:37

标签: php oop singleton crud

我想使用来自另一个类的数据库连接来调用类中的方法。

initializing.php

// load the configs, AFTER this I SHOULD HAVE CONSTANTS
require_once('myconfigs.php');

// load some function , some HELPER
require_once(LIB_PATH.DS.'functions.php');

// load the core objects
require_once(LIB_PATH.DS.'database.php');
$database = MySQLDatabaseConnection::connection();

the database.php

require_once('myconfigs.php');

require_once(LIB_PATH.DS.'initializing.php');

class MySQLDatabaseConnection {

    private static $instance;

    private function __construct(){

    }

    private function __clone(){

    }

    public static function connection(){

        if ( !isset( self::$instance ) ) {
            self::$instance = new MySQLi(DBSERVER, DBUSER, DBPASSWORD, DBNAME);
            if ( self::$instance->connect_error ) {
                throw new Exception('MySQL connection failed: '. self::$instance->connect_error);
            }
        }

        return self::$instance;

    }



}

the listproducts.php

这是一些测试,在DbPlus类之后,我想创建CRUD方法,但看起来简单的回声不起作用:/

require_once('initializing.php');

class DbPlus extends MySQLDatabaseConnection{

    public $database = parent::connection();

    public function read(){
        $query = "SELECT name, price_in, price_out, category_products_id FROM products";
        $data = $database->query($query);

        while ( $row = $data->fetch_object()) {
            echo $row->name;
        }
    }

}

$dbplus = new DbPLus;
$dbplus->read();

我收到此错误

  

解析错误:语法错误,意外情况'(',期待','或&#39 ;;' in   第19行的D:\ XAMPP \ htdocs \ xxx \ includes \ listproducts.php

我不知道哪里出乎意料的'('来自。

有什么想法吗?谢谢

2 个答案:

答案 0 :(得分:0)

listproducts.php

的一些严重问题

您应该在constructor

上执行此分配
public $database = parent::connection(); //<--- This gave you a syntax error.

喜欢这个......

  public $database;
    function __construct()
    {
     $this->database = parent::connection();
    }

接下来发生的是read(),您需要使用$this关键字..

应该是..

public function read(){
        $query = "SELECT name, price_in, price_out, category_products_id FROM products";
        $data = $this->database->query($query);   //<---- Do this way..

固定代码..

<?php
require_once('initializing.php');

class DbPlus extends MySQLDatabaseConnection{

    public $database;
    function __construct()
    {
     $this->database = parent::connection();
    }

    public function read(){
        $query = "SELECT name, price_in, price_out, category_products_id FROM products";
        $data = $this->database->query($query);

        while ( $row = $data->fetch_object()) {
            echo $row->name;
        }
    }

}

$dbplus = new DbPLus;
$dbplus->read();

答案 1 :(得分:0)

尝试这样的事情让我知道:

$dbplus = new DbPLus();
$dbplus->read();

同时向我们提供您正在使用的PHP版本