我正在寻找一个更好的解决方案。
我想从调用多个类来执行各种任务的主脚本开始记录日志。我希望所有被调用的类共享日志实例,并向日志中添加消息。
例如:主脚本:<?php
include 'log.php'
include 'classA.php'
include 'classB.php'
// start new logs
$log = new log('my_log_file.log');
$log->addMessage('log added outside any classes');
// continue loggin within other classes
$task_a = new classA($log);
$task_b = new classB($log);
是classA: <?php
class classA {
function __construct($log="") {
if(is_object($log)) {
$log->AddMessage("log added from within classA");
}
}
}
有什么更好的方法?
您可以考虑创建注册表类并将日志对象放入其中
<?php
include 'registry.php';
include 'log.php';
include 'classA.php';
include 'classB.php';
// start new logs
$registry = new registry();
$registry->addLogger(new log('my_log_file.log'));
$registry->getLogger->addMessage('log added outside any classes');
// continue loggin within other classes
$task_a = new classA($registry);
$task_b = new classB($registry);
类a.php <?php
class classA {
function __construct($registry="") {
if(is_object($registry)) {
$registry->getLogger()->AddMessage("log added from within classA");
}
}
}
有什么好处?如果你决定你需要传递给其他类其他对象,例如数据库连接,应用程序配置或其他,你只需修改注册表,添加到注册表的新对象(例如addDatabase),你将能够有数据库连接的所有类,你已经传递注册表对象。
当然你可以对某些类对象只传递选定的注册表对象而不是整个注册表
一些不错的回复,谢谢。对于我的需求,我坚持我最初的要求,因为没有其他建议比我已经拥有的更好。
创建一个php全局$log
http://php.net/manual/en/reserved.variables.globals.php