【问题标题】:Use of undefined constant - Learning OOP PHP未定义常量的使用 - 学习 OOP PHP
【发布时间】:2011-11-06 05:00:37
【问题描述】:

未定义的常量问题不是一个新问题,我已经尝试过 Google,发现有一百万个答案涉及缺少引号的数组,这不是我的解决方案。我正在学习使用 PHP 进行 OOP 编码,这实际上是我使用它的最初几个小时。这是我创建的类。

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');
    }
}



}

这就是我实例化它的方式。

include('class.template.php'); 

$template = new template();

$template->getHeader();

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

$template->getPage();



$template->getFooter();

当然还有错误 - 注意:使用未定义的常量页面 - 在第 24 行的 /Applications/MAMP/htdocs/titan-up/class.template.php 中假定为“页面”

这显然是我应该立即发现的,我做错了,但为时已晚,我不知所措。非常感谢任何帮助。

编辑:任何使学习过程更容易的链接将不胜感激。我已经在阅读它的 PHP 手册,并且在 PHP 方面有很强的背景,但不是 OOP。

【问题讨论】:

标签: php oop


【解决方案1】:

从此改变:

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

到这里:

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

错误消息“注意:使用未定义的常量页面 - 假定为“页面””并没有太大帮助,但不幸的是,PHP 会将未知标记隐式转换为具有相同值的常量。

这就是它看到page(它前面没有$,因此不是变量名)并将其视为之前的语句define('page', 'page');

注意:此错误消息的另一个常见原因是如果您忘记将字符串括在引号中 - 例如 $some_array[some_key] 而不是 $some_array['some_key']

【讨论】:

  • 就是这样。我开始的教程没有以这种方式使用它,但基于我有限的知识,这确实是有道理的。感谢您的帮助。
  • 啊,错误本身现在完全有意义了。我在想我定义值的方式有问题。
猜你喜欢
  • 2019-09-18
  • 2015-11-17
  • 2016-08-19
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-13
相关资源
最近更新 更多