PHP CONSTRUCTOR

Sugar babies

 PHP CONSTRUCTOR

  • A constructor allows you to initialize an object's properties upon creation of the object.
  • If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
  • Constructors are the very basic building blocks that define the future object and its nature.
  • You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables.
  • Constructors are special member functions for initial settings of newly created object instances from a class.

SYNTAX OF CONSTRUCTOR IN PHP :

<class-name>: :<class-name> (list-of-parameters){ // constructor definition }

EXAMPLE FOR CONSTRUCTOR IN PHP :

< ! DOCTYPE html>
<html>
<body>

<?php
class Fruit {
    public $name ;
    public $color ;

    function __construct ( $name ) {
        $this->name = $name ;
    }
    function get_name( ) {
       return $this->name;
     }
}

$apple = new Fruit ( "Apple" ) ;
echo $apple -> get_name( );
?>

</body>
</html>

OUTPUT :

Apple 
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send