访问类中的数据库对象时如何避免全局变量?
在类中使用全局变量
创建分页功能涉及从类中访问数据库对象。但是,尝试访问类内部的外部变量可能会导致错误。让我们深入研究处理此问题的可能解决方案。
为了解决致命错误“调用非对象上的成员函数 query()”,数据库对象需要在类中可访问。不使用全局变量,更合适的方法是将数据库对象注入到类或其方法中。
依赖注入
一种方法是注入数据库对象放入类构造函数中,如下所示:
include_once("pagi.php"); $db = new DB_MySQL("localhost", "root", "", "test"); // connect to the database $pagination = new Paginator($db); $records = $pagination->get_records("SELECT * FROM `table`"); class Paginator { protected $db; public function __construct(DB_MySQL $db) { $this->db = $db; } public function get_records($q) { $x = $this->db->query($q); return $this->db->fetch($x); } }
这允许分页类访问数据库对象
方法注入
另一种选择是将数据库对象注入到需要它的特定方法中:
$pagination = new Paginator(); $records = $pagination->get_records("SELECT * FROM `table`", $db); class Paginator { public function get_records($q, DB_MySQL $db) { $x = $db->query($q); return $db->fetch($x); } }
这提供了更多当多种方法具有不同的数据库要求时的灵活性。
依赖的好处注入
与使用全局变量相比,依赖注入有几个优点:
- 显式定义的依赖关系:明确哪些对象依赖于其他对象,消除隐藏的依赖关系。
- 松散耦合性: 该类可以轻松切换到不同的或模拟的数据库对象以进行测试。
- 可测试性: 单元测试可以仅关注该类,而不会干扰数据库功能。
- 扩展性:无需主要代码即可使用多个数据库或其他框架变化。
以上是访问类中的数据库对象时如何避免全局变量?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Stock Market GPT
人工智能驱动投资研究,做出更明智的决策

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

useunSerialize(serialize($ obj))fordeepcopyingwhenalldataiSerializable;否则,exhiment__clone()tomanallyDuplicateNestedObjectedObjectSandAvoidSharedReference。

usearray_merge()tocombinearrays,oftritingDupritingDuplicateStringKeySandReIndexingNumericKeys; forsimplerconcatenation,尤其是innphp5.6,usethesplatoperator [... $ array1,... $ array2]。

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

__call()methodistred prightedwhenaninAccessibleOrundEfinedMethodiscalledonAnaBject,允许customhandlingByAcceptingTheMethodNameAndarguments,AsshoheNpallingNengallingUndEfineDmethodSlikesayHello()

本文深入探讨了在MySQL中如何利用CASE语句进行条件聚合,以实现对特定字段的条件求和及计数。通过一个实际的预订系统案例,演示了如何根据记录状态(如“已结束”、“已取消”)动态计算总时长和事件数量,从而克服传统SUM函数无法满足复杂条件聚合需求的局限性。教程详细解析了CASE语句在SUM函数中的应用,并强调了COALESCE在处理LEFT JOIN可能产生的NULL值时的重要性。

usepathinfo($ fileName,pathinfo_extension)togetThefileextension; itreliablyhandlesmandlesmultipledotsAndEdgecases,返回theextension(例如,“ pdf”)oranemptystringifnoneexists。

toupdateadatabaseRecordInphp,firstConnectusingpDoormySqli,thenusepreparedStatementStoExecuteAsecuteAsecuresqurupDatequery.example.example:$ pdo = newpdo(“ mySql:mysql:host = localHost; localhost; localhost; dbname; dbname = your_database = your_database',yous_database',$ username,$ username,$ squeaste;
