Undefined variable notice in __construct

721 views Asked by At

Im getting an error at the class' __construct, says:

Notice: Undefined variable: DEFAULT_TOP_PAGE_ID in classes.php on line XY.

Here is the code:

// consts.php
    <?php
    $DEFAULT_TOP_PAGE_ID = "top_";
    ...

// classes.php
    <?php
    error_reporting (E_ALL);
    require_once("consts.php");

    class cSiteManager {
      public $top_page_ID;

      public function __construct() {
        $this->top_page_ID = $DEFAULT_TOP_PAGE_ID;
    ...

Can anyone tell me where the problem lies?

3

There are 3 answers

1
AudioBubble On BEST ANSWER

Variables have scope. If you're trying to use a variable inside a function it will be local to the function. To use one from outside the function you need to declare it as global.

function someFunc() {
  global $DEFAULT_TOP_PAGE_ID;
  // more code...
  $this->top_page_ID = $DEFAULT_TOP_PAGE_ID;
  // etc.

}

In this case I think you probably need a definition:

define("DEFAULT_TOP_PAGE_ID", "top_");

then

function someFunc() {
  // more code...
  $this->top_page_ID = DEFAULT_TOP_PAGE_ID;
  // Note: $ has gone  ^ here
  // etc.

}
1
Devon Bessemer On

Research scopes. $DEFAULT_TOP_PAGE_ID would have to be defined in the class or the method (function). If defined in the class, you would need to access it via $this-> like you have with top_page_ID.

3
bishop On

The variable $DEFAULT_TOP_PAGE_AD appears to be defined as a global. Conseqeuently, you have to declare it global in the constructor:

public function __construct() {
    global $DEFAULT_TOP_PAGE_AD;
    $this->top_page_ID = $DEFAULT_TOP_PAGE_AD;
}