3

I have created a Page class and all the pages on my website are objects of that Page class. Each Page object has a title attribute which is passed in as an argument to the constructor and so creating a new Page object looks as follows.

<?php

require_once('library/Page.php');

$page = new Page('About');

$page->header();

This is where the problem arises.

The header() method is...

public function header()
{   

    require_once($this->templatePath . 'header.php');

}

I then echo the page title using

<?php echo $page->title; ?>

However, I get the following error.


Notice: Undefined variable: page in /Users/aaronfalloon/Projects/PHP/tfm/template/header.php on line 19

Notice: Trying to get property of non-object in /Users/aaronfalloon/Projects/PHP/tfm/template/header.php on line 19

1
  • It's difficult to diagnose a class that none of us have seen. Show us what's going on within your class. Commented Dec 26, 2009 at 0:38

4 Answers 4

2

Let me further explain about what Gumbo has written.

When you included the template file, you did the operation WITHIN the header function, thus making all $page variable in the template file referring to the local $page variable in the header function, which apparently is not declared/defined.

You should use $this->title instead to refer to the current class.

It is something like

class Page{

  public function header(){
    echo $this->title;
  }

}

when you try to include the template file:

// page class
class Page{

  public function header(){
    include('template.php');
  }

}

.

// template file
echo $this->title;
Sign up to request clarification or add additional context in comments.

Comments

2

Use $this->title instead of $page->title since you refer to the property of the very same instance.

Comments

0

I'm not sure, it may be possible to solve this issue by adding global $page; before the require_once call in your Page::header function.

The require_once includes the code of the specified file and execute it keeping the current scope. In your Page::header function, $page is not visible.

Comments

0

$page is declared as a global and the header.php code has only local scope to the method.

Either: Use global $page after the method declaration before the require_once.
Pass $page into the header function as an argument public function header($page).
Use echo $this->title in header.php.

Or if you really want to screw around use extract(get_object_vars($this)) and echo $title.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.