php 对象加入子对象,php – 在父函数中调用子对象

我想知道如果我可以在父函数中调用子对象.像这样:

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();

这两个类在不同的文件中. My Child类正在使用函数B()与我的数据库建立连接.在我的Parent的类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());

}}

}

所以这是来自Above的Class Child,而Connect()是B().

现在是父母

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(<>, $this->query)

or die(mysqli_error(<>));

if($this->result == 1){

echo "
Your data were processed";

} else {

echo "
We are sorry but an error occurred";

}

$this->close_db();

}

在mysqli_query中我需要一个参数作为mysqli,它是与我的数据库的连接.该参数位于Child的类$dbc中,并在函数Connect()中调用它:$this-> dbc. mysqli_error也是如此.希望这会让事情更加清晰:).

解决方法:

考虑到你已经标记了这个oop,我会咬人.

没有理由将db_connect称为扩展名为Model的东西.更不用说没有理由把一些不会告诉任何人的模型称为什么,因此对于任何东西都是一个非常糟糕的名字.

其次,据我所知,你没有理由将mysqli包装开始.你可以通过包裹这样的物体获得什么. mysqli带有一个开箱即用的面向对象的界面.

最后当你摆脱那个奇怪的继承树时,你应该将数据库连接注入到需要它的类中.就像是:

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注入攻击.

标签:php,oop,design-patterns,oop

来源: https://codeday.me/bug/20190611/1219371.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值