0

These are my first steps in OOP php.

I have this class in my CMS.

class Pages
{
 private static $oInstance = null;
  public static function getInstance( ){
    if( !isset( self::$oInstance ) ){  
      self::$oInstance = new Pages( );  
    }  
    return self::$oInstance;  
  } // end function getInstance

  /**
  * Constructor
  * @return void
  */
  private function __construct( ){
    $this->generateCache( );
  } // end function __construct

  /**
  * Generates cache variables
  * @return void
  */
  public function generateCache( ){
    //some more code

}
};

I want to create my class extending Pages to make use of its properties and methods:

class New extends Pages{

 private static $oInstance = null;
 public static function getInstance( ){
 if( !isset( self::$oInstance ) ){  
   self::$oInstance = new Ajax( );  
}  
 return self::$oInstance;  
} 

public function newmethod(){

//some logic
}
};

However when i attempt to initialize Object, php just generates blank page (even without error).

$object = New::getInstance( );

or

$object = new New();

What am I doing wrong? If I remove constructor from parent and child class at lest page renders.

Stack Player
  • 1,420
  • 2
  • 17
  • 31
user3667832
  • 237
  • 1
  • 5
  • 15
  • 2
    read this : http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12772851#12772851 – mmm Aug 23 '15 at 20:46
  • 1
    Try changing your constructor to a protected method instead of private. Private methods cannot be used by sub classes. – Nilithus Aug 23 '15 at 21:00

2 Answers2

3

The class New does not declare a constructor. This means it inherits the constructor from the base class. But the constructor of the base class is private and that restricts its usage to the methods of its class.

The solution is to declare the constructor of class Pages as protected. This way it can be called by the methods of the derived classes.

More, if a class is not declared as final (this prevents extending it) then it must not declare its constructor as private. Having the constructor private prevents the constructor of the children classes to call it and this lets the properties of the base class uninitialized (i.e. the objects of the derived classes are not properly constructed).

Declaring the constructor as private is a bad practice. It requires having a static method of the class that acts as a factory of objects of that class (the method getInstance() in your case) and this makes the class difficult to test and impossible to replace with a mock in a test.

axiac
  • 56,918
  • 8
  • 77
  • 110
0

I suppose that in your New-class you mean

self::$oInstance = new New( );
PhilMasterG
  • 2,425
  • 1
  • 16
  • 22