The Constructor method is a special type of function called __construct within the class body.
To declare /create a constructor method, use the __construct name (begins with two underscore "__").
This method is always "public" even if this attribute is not specified.
The difference from the other functions is that a constructor method is automatically invoked when an object is created.


- Here's a new version of the SiteClas class (created in the previous lesson) which has declared a constructor method, also it has two properties and two methods.
<?php
// SiteClas class
class SiteClas {
  public $site = 'coursesweb.net/';         // public property
  private $category = 'php-mysq/';             // private property

  // Define constructor
  public function __construct($name) {
    // outputs a message, including the "site" property
    echo 'Welcome '. $name. ' on '. $this->site. '<br />';
    echo $this->Mesaj();       // adds and returns the Mesaj() method
  }

  // protected method
  protected function Mesaj() {
    // return a message includind the 'category' property
    return 'Web site category: '. $this->category;
  }

  // public method, receive an argument
  public function pages($pag) {
    // output the URL address consists of the value of the two properties and its argument
    echo '<br />'. $this->site. $this->category. $pag;
  }
}
?>
The constructor method uses the pseudo-variable $this to access the elements of its class (here "site" property and the Mesaj() method).
Because the constructor method has a parameter ($name) [you can add more parameters or none, as any function], when it creates an object instance of the class you must add and an argument too.

-The following example includes the SiteClas class (saved in the "class.SiteClas.php" file), and instantiate an object.
<?php
include('class.SiteClas.php');        // Include SiteClass class

// create an object of SiteClass, with one argument
$objSite = new SiteClas('Marius');
?>
When the $objSite is set, the constructor method receives the argument ('Marius') and executes its code.
Output:
Welcome Marius on http://coursesweb.net/
Web site ategory: php-mysq/

Setting optional parameters

If the constructor method is defined with a number of parameters, without an initial value, when the object instance is created, the class must be called with the same number of arguments, otherwise return error.
For example, the constructor method defined in the previous example has one parameter ($name), if you create an instance of SiteClas without argument, like:
          $obj = new SiteClass();
will generate an error like:
Warning: Missing argument 1 for SiteClas::__construct(), called in ...

You can declare parameters with an initial value, so the arguments for them become optional.
  - Example (a class named Test which has a constructor with an optionl argument ( $name='You' ) ):
<?php
class Test {
  // Constructor (a parameter with default value)
  public function __construct($name='You') {
    echo '<br />Hy '. $name;
  }
}
?>
- If the instance of the Test class is created without argument, the constructor method will use the "$name" parameter with its initial value ("You"), but when an argument is passed, the constructor uses its value.
The example below creates two object instances of the Test class, one without argument, and the other with an argument.
  - Example:
<?php
// object instance without argument
$obj1 = new Test();

// object instance with argument
$obj2 = new Test('Marius');
?>
- This example also demonstrate that you can create multiple object instances of the same class.
Output:
Hy You
Hy Marius

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag renders as emphasized text, displaying the text oblique?
<strong> <pre> <em>
<p>Web development courses: <em>CoursesWeb.net</em></p>
Which CSS property defines the space between the element border and its content?
margin padding position
h3 {
  padding: 2px 0.2em;
}
Click on the method which returns the first element that matches a specified group of selectors.
getElementsByName() querySelector() querySelectorAll()
// gets first Div with class="cls", and shows its content
var elm = document.querySelector("div.cls");
alert(elm.innerHTML);
Indicate the PHP variable that contains data from a form sent with method="post".
$_SESSION $_GET $_POST
if(isset($_POST["field"])) {
  echo $_POST["field"];
}
PHP OOP - Constructor Method

Last accessed pages

  1. Action Games (1456)
  2. Adventure Games (1127)
  3. Escape Games (1391)
  4. Display data from PHP Array, or MySQL in HTML table (8659)
  5. Flash Games - Free online Games (4446)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (43447)
  2. PHP-MySQL free course, online tutorials PHP MySQL code (33041)
  3. Read Excel file data in PHP - PhpExcelReader (32967)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (29817)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (27129)