Object Oriented PHP(php oop) Part 03-php constructor - Web Development and Web Design Codes

Latest

Tuesday, February 6, 2018

Object Oriented PHP(php oop) Part 03-php constructor

PHP Constructor


php constructor
php constructor

Constructor in PHP OOP is special type of function of a class which is automatically executed 

 any object of that class is created


In PHP4, we create constructor by class name it means the name of constructor is same as the class name but in PHP5, it has been changed to create constructor, it can be initialized by `__construct` keyword. note: constructor start with __ Double Underscore() .example: 
function __construct(){
}


PHP Constructor Examples:

Example 1:
<?php
class Blog{
	public $title;
	public $author;
 public function __Construct($title,$author){
	 $this->title=$title;
	 $this->author=$author;
 }
 public function Getinfo(){
	 echo 'Position:=> '.$this->title .' | Name: => '. $this->author;
 }
}

$obj=new Blog('Jobs','ANJAN KUMAR');
echo $obj->Getinfo();

?>

Example 2:
<?php
class Blog{
	public $title;
	public $author;
	public $skill;
	public $salary;
 public function __Construct($title,$author,$skill,$salary){
	 $this->title=$title;
	 $this->author=$author;
	 $this->skill=$skill;
	 $this->salary=$salary;
 }
 public function Getinfo(){
	 echo 'Position:=> '.$this->title .' | Name: => '. $this->author .'|
	 Skill=> '.$this->skill .'| Salary=> ' .$this->salary;
 }
}

$obj=new Blog('Jobs','ANJAN KUMAR','PHP,Codeigniter,JAVA','$5000');
echo $obj->Getinfo();

?>
Why is php constructor helpful? 
Because instead of:

$obj = new Blog();
$obj->title='Jobs';
$obj->author='ANJAN KUMAR';
you can use:

$obj = new Blog('Jobs','ANJAN KUMAR');

Which is less code and looks cleaner..
Keep visiting this blog for more php oop examples .Thank you for visiting... 

No comments:

Post a Comment

Thank You for Your Comment

Note: Only a member of this blog may post a comment.