Constructors

Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class will be called, if it exists.

<?php

class Auto_Cart extends Cart {

function Auto_Cart() {

$this->add_item("10", 1);} }

?>

This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can take arguments and these arguments can be optional, which makes them much more useful. To be able to still use the class without parameters, all parameters to constructors should be made optional by providing default values.

<?php

class Constructor_Cart extends Cart {

function Constructor_Cart($item = "10", $num = 1) {

$this->add_item ($item, $num);

}

}

// Shop the same old boring stuff.

$default_cart = new Constructor_Cart;

// Shop for real...

$different_cart = new Constructor_Cart("20", 17);

?>

Destructors are functions that are called automatically when an object is destroyed, either with unset() or by simply going out of scope. There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors.


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: