質問

I'm very new to php constructors I know of from java. But for some reason, this one is not running. I am following a tutorial and I can't seem to get a 1 only a 0. Here are the two scripts involved:

<?php

class dbConnection{
    protected $db_conn;
    public $db_name = 'todo';
    public $db_user = 'root';
    public $db_pass = '';
    public $db_host = 'localhost';

    function connect(){
        try{
            $this->db_conn = new PDO("mysql:host=$this->db_host;db_name=$this->db_name",$this->db_user,$this->db_pass);
            return $this->db_conn;
        }
        catch(PDOException $e)
        {
            return $e->getMessage();
        }
    }

}

?>

<?php

include_once( 'class.database.php' );

class ManageUsers {
    public $link;
    public $constructed;

    function ManageUsers(){
        $db_connection = new dbConnection();
        $this->link = $db_connection->connect();
        return $this->link;
    }

    function registerUser($username,$password,$ip_address,$time,$date){
        $query = $this->link->prepare("INSERT INTO users (username,password,ip_address,time,date) VALUES (?,?,?,?,?)");
        $values = array($username,$password,$ip_address,$time,$date);
        $query->execute($values);
        $counts = $query->rowCount();
        return $counts;
    }
}


$users = new ManageUsers();

echo $users->registerUser('bob','bob','127.0.0.1','10:00','29-02-2012');
?>
役に立ちましたか?

解決

You should try to use __construct() instead for ManageUsers().

Also, I'm not quite sure what you're trying to achieve in your constructor (see my markings below):

function ManageUsers(){
    $db_connection = new dbConnection();
    $this->link = $db_connection->connect();
    return $this->link; //<--?
    $constructed = 'Construct'; //<--?
}

他のヒント

Agreed - the method you are using is the old school PHP4 method - you should use the __construct() method as explained above.

http://www.php.net/manual/en/language.oop5.decon.php

This page explains construct() & destruct() in PHP 5

// constructor
function __construct() {
 ManageUsers();
}


function ManageUsers(){
    $db_connection = new dbConnection();
    $this->link = $db_connection->connect();
    $constructed = 'Construct';
}

You cannot return from a constructor tho, maybe you can want to make link a public property and access it directly like this

$user = new ManageUsers();
$link = $user->$link;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top