简体   繁体   中英

Use of undefined constant - Learning 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.

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'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM