对于我从java中了解到的php构造函数,我是一个新手。但出于某种原因,这个没有运行。我正在按照教程进行操作,似乎只能1
0
。以下是涉及的两个脚本:
<?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');
?>
答案 0 :(得分:1)
您应该尝试使用__construct()
代替ManageUsers()
。
另外,我不太确定你在构造函数中想要实现的目标(参见下面的标记):
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link; //<--?
$constructed = 'Construct'; //<--?
}
答案 1 :(得分:1)
同意 - 您使用的方法是旧式PHP4方法 - 您应该使用__construct()方法,如上所述。
http://www.php.net/manual/en/language.oop5.decon.php
此页面解释了construct()&amp; PHP 5中的destruct()
答案 2 :(得分:0)
// constructor
function __construct() {
ManageUsers();
}
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
$constructed = 'Construct';
}
你不能从构造函数返回,也许你可以想要链接一个公共属性并直接访问它
$user = new ManageUsers();
$link = $user->$link;