我想知道我是否可以在父函数中调用子对象。像这样:
class Parent {
public function A() {
<< I want to call the object here >>
// Some code
}
}
Class Child extends Parent {
public function B() {
// Some code
}
}
$Child = new Child();
$Child -> B();
这两个类在不同的文件中。我的子类正在使用函数 B() 与我的数据库建立连接。在我的父类 A() 中,我试图插入从填写表单中收到的数据,但我需要连接到数据库,但我不知道如何调用该对象。注意:当我在同一个类中同时拥有这两个函数时,我的代码可以正常工作。
我没有找到解决方案,所以我会尝试并发布我的真实代码:
class db_connect extends Model
{
private $dbname = "...";
private $dbuser = "...";
private $dbpass = "...";
private $dbhost = "...";
public $dbc;
public function Connect()
{
$this->dbc = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if($this->dbc === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}}
}
所以这是 Class Child from Above 而 Connect() 是 B()。
现在是 parent
class Model
{
public $query;
public $result;
public function proccess_data($marca,$model,$pret,$descriere){
<< I am trying to make a connection here from config.php using the function Connect() >>
$this->query = "INSERT INTO autoturisme (autoturism_id, marca, model, pret, descriere) " .
"VALUES (NULL, '$marca', '$model', '$pret', '$descriere')";
$this->result = mysqli_query(<<Also here I would need the connection>>, $this->query)
or die(mysqli_error(<<And here>>));
if($this->result == 1){
echo "<br/>Your data were processed";
} else {
echo "<br/>We are sorry but an error occurred";
}
$this->close_db();
}
在 mysqli_query 中,我需要一个参数作为 mysqli,它是到我的数据库的连接。该参数位于子类 $dbc 中,并在函数 Connect() 中调用:$this->dbc。 mysqli_error 也是如此。希望这能让事情更清楚 :)。
最佳答案
考虑到您已标记此 oop我会咬。
db_connect
没有理由扩展Model
。更不用说没有理由称某些东西为 Model
,它不会告诉任何人任何东西,因此对于任何东西来说都是一个非常蹩脚的名字。
其次,据我所知,您没有理由在开始时包装 mysqli
。通过包装这样的对象你会得到什么。 mysqli
带有开箱即用的面向对象的接口(interface)。
最后,当你摆脱了你正在进行的那个奇怪的继承树时,你应该将数据库连接注入(inject)到需要它的类中。像这样的东西:
class Car
{
// why do you need a `$query` member when you are not going to use it?
// same for `$result`
private $dbConnection;
public function __construct(mysqli $dbConnection)
{
$this->dbConnection = $dbConnection;
}
public function add($marca, $model, $pret, $descriere)
{
$query = 'INSERT INTO autoturisme';
$query.= ' (marca, model, pret, descriere)';
$query.= ' VALUES';
$query.= ' (?, ?, ?, ?)';
$stmt = $this->dbConnection->prepare($query);
$stmt->bind_param('ssss', $marca, $model, $pret, $descriere);
if (!$stmt->execute()) {
throw new \Exception('We are sorry but an error occurred');
}
}
}
$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');
$car = new Car($mysqli);
try {
$car->add('BMW', '325', 'dunnowhatthismeans', 'description?');
} catch(\Exception $e) {
echo $e->getMessage();
}
另请注意,您的代码很可能容易受到 SQL 注入(inject)攻击。
关于php - 在父函数中调用子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209806/