Abstract Classes and Constructors

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Son Volt
Forum Newbie
Posts: 19
Joined: Tue Jul 11, 2006 1:36 pm

Abstract Classes and Constructors

Post by Son Volt »

If I have an abstract class, I assume since it can't be instantiated there is no constructor for the class. I want to make sure each class that extends from this abstract class defines a constructor. Does that mean I need to define an abstract method called __construct() in my abstract class to force this?

Code: Select all

abstract class Person{
    
    protected $name;

    function getName(){
        return $this->name;
    }
   
    abstract function __construct(); //enforce constructor here???
}


class Employee extends Person{
    
    function __construct(){ 
        $this->name = "john";
    }
}
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Yes, defining __contruct() as abstract will require that a constructor exists and give a fatal error if it is missing.
(#10850)
Post Reply