解决方案1
替换
class account_info {为class account_info extends connection {更换
$con = new connection();$info = new account_info();
与
$info = new account_info();
它应该工作。
解决方案2(建议)
我强烈建议您在这种情况下使用依赖项注入来解决您的问题。只需将您的帐户类别替换为:
class account_info { private $con; public function __construct(connection $con) { $this->con = $con->con; } public function getAccountInfo(){ $acc_info = $this->con->prepare("SELECt * FROM account_info"); $acc_info->execute(); $results = $acc_info->fetchAll(PDO::FETCH_OBJ); foreach ($results as $key) { $results->owner_firstname; } }}并像这样在index.php中使用它:
include_once 'classes/connection.class.php';include_once 'classes/accountinfo.class.php';$con = new connection();$info = new account_info($con);$info->getAccountInfo();
说明
通常的规则是:始终为函数(公共,保护或私有)指定作用域关键字。
第一个解决方案称为继承,而我们所做的基本上是用连接类扩展account类,以便从连接类继承所有方法和属性并轻松使用它们。在这种情况下,您必须提防命名冲突。我建议您看一下PHP手册中的类继承。
第二种解决方案称为依赖注入,这是一种强烈鼓励的设计模式,它使您的类在其构造函数中接受其他类,以便显式定义类依赖关系树(在这种情况下,帐户依赖于连接,没有连接我们就无法使帐户正常运行)。
在成千上万的可能解决方案中,另一个是某人在下面发布的解决方案,该设计模式称为Singleton。但是,该模式最近已重新评估为反模式,因此不应使用。



