__construct & __destruct and Magic Methods in PHP

Leave a Comment


This post using PHP to do objected oriented programming. The PHP has more than 9 magic methods, but these will get you off to a good start using PHP's magic methods.

The "magic" methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.

1)  __construct

The constructor is a magic method that gets called when the object is instantiated. It is usually the first thing in the class declaration but it does not need to be, it a method like any other and can be declared anywhere in the class. Constructors also inherit like any other method.

2) __destruct

The __destruct method does the opposite of the constructor. It gets run when the object is destroyed.

Example:
class A{        protected $_id = null;        public function __construct($id) {                $this->_id = $id;                return $this;        }        public function __destruct() {                echo "object is destroyed";        }}
$obj = new A(3);


0 comments:

Post a Comment