dongtong2021 2013-03-21 23:39 采纳率: 0%
浏览 31

PHP:类之间传递的动态变量

My apologies if my title is not clear, please let me explain...

I have a template class call 'page', when I initialize it I can set it up to be in debug mode by setting $mode.

The problem is I also have a database class and I would like to share the fact that 'page' is in debug mode but don't know the best way to do it...I cannot have 'page' extends 'db' and no where does 'page' actually call the 'db' class. It is always happening on other classes.

Again, sorry if this is unclear...I tried to provide a really simple version of the code to help...

class page {
    public $mode; // what mode the page is in (debug/normal)

    public function __construct($constructVars) {
        $this->mode = $constructVars["mode"]; //debug
    }

    public function debug($message){
        if ($this->mode == "debug"){
            $fh = fopen("debug.txt", 'a') or die("can't open debug file");
            fwrite($fh, date("Y-m-d H:i:s")." : ".$message."
");
            fclose($fh);
        }
    }
}

class db extends PDO {
    public function debugOutput() {
        $page = new page();
        if ($page->mode == "debug"){
            $fh = fopen("debug.txt", 'a') or die("can't open debug file");
            fwrite($fh, $message."
");
            fclose($fh);
        }
    }
 }

Just to reiterate because I think it is the answer that is going to come up, I can not extend page to include db.

  • 写回答

2条回答 默认 最新

  • 普通网友 2013-03-22 00:28
    关注

    I would use a Static Class to store globally accessible stuff like this:

    class SystemState{
        public static $debugMode = false; // what mode the page is in (debug/normal)
    }
    
    class page {
    
        public function __construct($constructVars) {
            if($constructVars["mode"] == 'debug'){
                SystemState::$debugMode = true;
            }
        }
    
        public function debug($message){
            if (SystemState::$debugMode){
                $fh = fopen("debug.txt", 'a') or die("can't open debug file");
                fwrite($fh, date("Y-m-d H:i:s")." : ".$message."
    ");
                fclose($fh);
            }
        }
    }
    
    class db extends PDO {
        public function debugOutput() {
            if (SystemState::$debugMode){
                $fh = fopen("debug.txt", 'a') or die("can't open debug file");
                fwrite($fh, $message."
    ");
                fclose($fh);
            }
        }
     }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害