0

I hava a class called DBhelper, and now I created a new class called UserManager. I need the UserManager have functions like GetUserId() and CheckValidation().So I require the DBhelper for those database actions. But I found it doesn't work like this:

require_once('DBhelper.php');
class User{
  public $databaseHelper = new DBhelper();//syntax error
  public $DB = $databaseHelper->connectDB();//syntax error

  public function GetUserId(){
    $this->databasesHelper->RunSql();//syntax error
    ...
  }
  public function CheckValidation(){
    $this->databasesHelper->RunSql();//syntax error
    ...
  }
}

Please halp me, I have searched the internet for long time. thanks.

2
  • 1
    Have you googled "Dependency Injection"? Commented Jun 15, 2012 at 14:18
  • no I haven't. But I do this after you say. However, it doesn't help. I know the concept of dependency injection but I don't know how to apply this in php. Thank you for your comment. Commented Jun 15, 2012 at 14:24

5 Answers 5

8

Try something like this, it uses the dependency injection design pattern.

class User {
    private $db;
    public function __construct(DBHelper $db) {
         $this->db = $db->connectDB();
    }

    public function GetUserId(){
        $this->db->RunSql();
    }

}

Here is how you instantiate it:

// Assuming: require( 'DBhelper.php');
$dbh = new DBHelper();
$user = new User( $dbh);

Also, to touch on your errors, these are errors (note they're not syntax errors, since they are syntactically correct):

public $databaseHelper = new DBhelper();//syntax error
public $DB = $databaseHelper->connectDB();//syntax error

Because you cannot initialize member variables to non-static values. So, since the values are not known at compile time, it is an error.

Similarly, these calls:

$this->databasesHelper->RunSql();//syntax error

Are invalid because $databasesHelper was never instantiated with a proper object.

Sign up to request clarification or add additional context in comments.

2 Comments

so i need to pass the whole DBhelper as $db to _construct?
@PandaYang: You only pass the object identifier, not the whole object in PHP. The object is just in memory somewhere, and it does not move away.
2

You need to instantiate your instance variables in a constructor or other appropriate method. You cannot declare and instantiate an instance variable like you have done.

Your code should look more like this:

require_once('DBhelper.php');
class User{
  public $databaseHelper;
  public $DB;

  public function User(){
    $this->databaseHelper = new DBHelper();
    $this->DB = $this->databaseHelper->connectDB();
  }
  public function GetUserId(){
    $this->databaseHelper->RunSql();//syntax error
    ...
  }
  public function CheckValidation(){
    $this->databaseHelper->RunSql();//syntax error
    ...
  }
}

Comments

1

You probably don't want to expose the database classes outside of your class and you can instantiate them in the constructor. Event better, you could pass them into the constructor so the User class doesn't even need to know how to instantiate them - something higher up the food chain can deal with their creation (especially if you will later have another class like User that needs them).

class User{
  private $databaseHelper;
  private $DB;

  public function __construct() {
      $this->databaseHelper = new DBhelper();
      $DB = $databaseHelper->connectDB();
  }

  public function GetUserId(){
    $this->databasesHelper->RunSql();
    ...
  }
  public function CheckValidation(){
    $this->databasesHelper->RunSql();
    ...
  }
}

2 Comments

In this case, every instance of a class (let's say class User) would create a NEW connection to the database, right ? This might be bad if we have 5 user object, as we also have 5 db connections now.
@Panique if you want to use a single connection, you should have logic in DBhelper to obtain the existing connection, rather than allowing the User class to decide whether to use an existing or new connection.
1

You can't assign value like that for propierties.
Create a constructor and assign the default value there

Comments

1

i have also did the same thing like yours. But i have declared my db class as following;

public class MySqlDatabase
{

private static $connection;

public static function openConnection()
{
    self::$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
    if(!self::$connection)
    {
        throw new Exception("Connection failed to database");
    }

    mysql_select_db(DB_NAME, self::$connection);
}


public static function closeConnection()
{
    if(isset(self::$connection))
    {
        mysql_close(self::$connection);
    }
}

public static function executeQuery($query)
    {
        $result = mysql_query($query, self::$connection);
        if(!$result)
        {
            throw new Exception("Query execution failed. " . $query);
        }

        return $result;
    }
}

and inside my other class i m calling them like this;

MySqlDatabase::openConnection();
MySqlDatabase::executeQuery();
MySqlDatabase::closeConnection();

so, i m saying that declare your database connection logic as a static. It will be than easy to access

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.