A Class is a blueprint of an object information. It defines the variables and methods that gives a collection of information. For example, lets just see some examples to know the structure of the class :
1 2 3 4 5 6 7 8 | <?PHP class animal { //define the class propertise go here } ?> |
An Object is a actual thing that create bases of a blueprint (class).
Properties of an object :
1 2 3 4 5 | <?PHP $obj = new animal(); ?> |
Bellow is the complete code that define a class and and an object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?PHP class animal { function display() { echo "Hello world!"; } } #create a object $obj = new animal(); $obj->display(); ?> |
Copy and paste that code and save as test.php and reloading your browser now you get the outputs the following:
Hello world!
PHP provides the magic method__construct() which called when you create an object of a class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php class animal { public $x = "I'm a class property!"; public function __construct() { echo 'The class "', __CLASS__, '" was initiated!<br />'; } public function setProperty($newval) { $this->x = $newval; } public function getProperty() { return $this->x . "<br />"; } } // Create a new object $obj = new animal; // Get the value of $prop1 echo $obj->gt;getProperty(); // Output a message at the end of the file echo "Output is here.<br />"; ?> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: How to create class and object in php, oops concept in php, PHP