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.
<?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).
<?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.
<?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.
<?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.
Some content ... <hr /> Content under line ...
h2 { color: #cbdafb; }
var str = "Web courses - http://CoursesWeb.net/"; if(str.indexOf("http://") == -1) alert("http:// isn`t in string"); else alert("http:// is in string");
$str = "apple,banana,melon,pear"; $arr = explode(",", $str); var_export($arr); // array (0=>"apple", 1=>"banana", 2=>"melon", 3=>"pear")