douxie0824 2011-11-06 05:00
浏览 41
已采纳

使用未定义的常量 - 学习OOP PHP

The undefined constant question isn't a new one, and I've tried Google already and found a million answers involving arrays with missing quotes and that's not my solution. I'm learning OOP coding with PHP and this is literally my first few hours working with it. This is the class I created.

class template {

var $page;

function __construct() {
    $this->page = 'home';
}

function getHeader($header = 'header') {
    include ('template/'.$header.'.php');
}

function getFooter($footer = 'footer') {
    include ('template/'.$footer.'.php');
}

function setPage($page = 'home') {
    $this->page = $page;
}

function getPage() {
    if(page === 'home') {
        include('template/home.php');
    } else {
        include('template/'.$this->page.'.php');
    }
}



}

And this is how I instantiated it.

include('class.template.php'); 

$template = new template();

$template->getHeader();

if(isset($_GET['page'])) {
    $template->setPage($_GET['page']);
}

$template->getPage();



$template->getFooter();

And of course the error - Notice: Use of undefined constant page - assumed 'page' in /Applications/MAMP/htdocs/titan-up/class.template.php on line 24

This is obviously something I should spot right away that I'm doing wrong but it's late and I'm at a loss. Any help is greatly appreciated.

Edit: Any links that make the learning process easier would be greatly appreciated. I'm already going through the PHP manual on it and have a strong background in PHP, but not OOP.

  • 写回答

1条回答 默认 最新

  • doucong6884 2011-11-06 05:03
    关注

    Change from this:

    function getPage() {
        if(page === 'home') {
    

    To this:

    function getPage() {
        if($this->page === 'home') {
    

    The error message "Notice: Use of undefined constant page - assumed 'page'" isn't terribly helpful, but it's due to the unfortunate fact that PHP will implicitly convert an unknown token as a constant with the same value.

    That is it's seeing page (which doesn't have a $ in front of it and therefore isn't a variable name) and treating it as though there was a previous statement define('page', 'page');.

    Note: Another common cause of this error message is if you forget to wrap a string in quotes - eg $some_array[some_key] instead of $some_array['some_key'].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料