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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么