Author: saqibkhan

  • Magic Constants

    The magical constants in PHP are predefined constants. They are available to any script on which they run, and they change depending on where they are used. All these “magical” constants are resolved at compile time, unlike regular constants, which are resolved at runtime.

    There are nine magical constants in PHP. These special constants are case insensitive.

    __LINE__

    It returns the current line number of the file. The following example shows how you can use this magic constant.

    Open Compiler

    <?php
       $x="Hello World";
       echo "$x. The current Line number is " . __LINE__ . ".";
    ?>

    It will produce the following output −

    Hello World. The current Line number is 5.
    

    __FILE__

    This magic constant returns the full path and filename of the file. If used inside an include, the name of the included file is returned. Take a look at the following example −

    Open Compiler

    <?php
       $x="Hello World";
       echo "$x. Current PHP script name is " . __FILE__ . ".";
    ?>

    It will produce the following output −

    Hello World. Current PHP script name is C:\xampp\htdocs\hello.php.
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    __DIR__

    This magical constant returns the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to “dirname(__FILE__)”. This directory name does not have a trailing slash unless it is the root directory. See the following example −

    Open Compiler

    <?php
       $x="Hello World";
       echo "$x. Directory of the Current PHP script name is " . __DIR__ . ".";
    ?>

    It will show the following output on the browser −

    Hello World. Directory of the Current PHP script name is C:\xampp\htdocs.
    

    __FUNCTION__

    This magical constant returns the function name in which the constant is used, or {closure} for anonymous functions. The following example shows how it works −

    Open Compiler

    <?php
       function hello(){    
    
      $x="Hello World";  
      echo "$x. The function name is ". __FUNCTION__ . "";   
    } hello(); ?>

    It will produce the following output −

    Hello World. The function name is hello
    

    If this magic constant is used outside the function, then it will give a blank output.

    __CLASS__

    This constant returns the name of a class. The class name includes the namespace it was declared in. See the following example −

    Open Compiler

    <?php
       class myclass {    
    
      public function __construct() {    
         echo "Inside the constructor of ". __CLASS__ . PHP_EOL;    
      }    
      function getClassName(){                      
         echo "from an instance method of " . __CLASS__ . "";   
      }    
    } $obj = new myclass; $obj->getClassName(); ?>

    It will produce the following output −

    Inside the constructor of myclass
    from an instance method of myclass
    

    __METHOD__

    The __METHOD__ constant returns the class method name. The following example shows how it works −

    Open Compiler

    <?php
       class myclass {    
    
      public function __construct() {    
         echo "Calling " . __METHOD__ . " of " . __CLASS__ ."&lt;br&gt;";
      }    
      function mymethod(){                      
         echo "Calling " . __METHOD__ . " of " . __CLASS__ ."";
      }    
    } $obj = new myclass; $obj->mymethod(); ?>

    It will produce the following output −

    Calling myclass::__construct of myclass
    Calling myclass::mymethod of myclass
    

    __TRAIT__

    It returns the trait name. The trait name includes the namespace it was declared in. In PHP, traits are a mechanism for code reuse. A trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a trait on its own.

    Take a look at the following example −

    Open Compiler

    <?php
       trait mytrait {
    
      public function hello() {
         echo "Hello World from " . __TRAIT__ ."";
      }
    } class myclass {
      use mytrait;
    } $obj = new myclass(); $obj->hello(); ?>

    It will produce the following output −

    Hello World from mytrait
    

    __NAMESPACE__

    This constant returns the name of the current namespace. In PHP, namespaces allow us to use classes / functions / constants of same name in different contexts without any conflict, thereby encapsulating these items. A namespace is a logical grouping of classes/functions depending on their relevance.

    The following example shows how you can use this magic constant −

    Open Compiler

    <?php
       namespace myspace;
       class myclass {    
    
      public function __construct() {    
         echo "Name of the class: " . __CLASS__ . " in " . __NAMESPACE__ . ""; 
      }     
    } $class_name = __NAMESPACE__ . '\myclass'; $a = new $class_name; ?>

    It will produce the following output −

    Name of the class: myspace\myclass in myspace
    

    ClassName::class

    Unlike the other magic constants, this magic constant does not start and end with the double underscore (__). It returns the fully qualified class name.

    The following example shows how you can use this magic constant −

    Open Compiler

    <?php
       namespace myspace;
       class myclass {    
    
      public function __construct() {    
         echo "Name of the class: " . myclass::class ;
      }     
    } use myspace; $a = new myclass; ?>

    It will produce the following output −

    Name of the class: myspace\myclass
    
  • Class Methods

    Methods belongs to an object of a class and used to perform specific operations. We can divide Python methods in three different categories, which are class method, instance method and static method.

    A Python class method is a method that is bound to the class and not to the instance of the class. It can be called on the class itself, rather than on an instance of the class.

    Most of us often get class methods confused with static methods. Always remember, while both are called on the class, static methods do not have access to the “cls” parameter and therefore it cannot modify the class state.

    Unlike class method, the instance method can access the instance variables of the an object. It can also access the class variable as it is common to all the objects.

    Creating Class Methods in Python

    There are two ways to create class methods in Python −

    • Using classmethod() Function
    • Using @classmethod Decorator

    Using classmethod() Function

    Python has a built-in function classmethod() which transforms an instance method to a class method which can be called with the reference to the class only and not the object.

    Syntax

    classmethod(instance_method)

    Example

    In the Employee class, define a showcount() instance method with the “self” argument (reference to calling object). It prints the value of empCount. Next, transform the method to class method counter() that can be accessed through the class reference.

    Open Compiler

    classEmployee:
       empCount =0def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
      Employee.empCount +=1defshowcount(self):print(self.empCount)
      
    counter =classmethod(showcount) e1 = Employee("Bhavana",24) e2 = Employee("Rajesh",26) e3 = Employee("John",27) e1.showcount() Employee.counter()

    Output

    Call showcount() with object and call count() with class, both show the value of employee count.

    3
    3
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Using @classmethod Decorator

    Use of @classmethod() decorator is the prescribed way to define a class method as it is more convenient than first declaring an instance method and then transforming it into a class method.

    Syntax

    @classmethoddefmethod_name():# your code

    Example

    The class method acts as an alternate constructor. Define a newemployee() class method with arguments required to construct a new object. It returns the constructed object, something that the __init__() method does.

    Open Compiler

    classEmployee:
    
    empCount =0def__init__(self, name, age):
        self.name = name
        self.age = age
        Employee.empCount +=1@classmethoddefshowcount(cls):print(cls.empCount)@classmethoddefnewemployee(cls, name, age):return cls(name, age)
    e1 = Employee("Bhavana",24) e2 = Employee("Rajesh",26) e3 = Employee("John",27) e4 = Employee.newemployee("Anil",21) Employee.showcount()

    There are four Employee objects now. If we run the above program, it will show the count of Employee object −

    4
    

    Access Class Attributes in Class Method

    Class attributes are those variables that belong to a class and whose value is shared among all the instances of that class.

    To access class attributes within a class method, use the cls parameter followed by dot (.) notation and name of the attribute.

    Example

    In this example, we are accessing a class attribute in class method.

    Open Compiler

    classCloth:# Class attribute
       price =4000@classmethoddefshowPrice(cls):return cls.price
    
    # Accessing class attributeprint(Cloth.showPrice())

    On running the above code, it will show the following output −

    4000
    

    Dynamically Add Class Method to a Class

    The Python setattr() function is used to set an attribute dynamically. If you want to add a class method to a class, pass the method name as a parameter value to setattr() function.

    Example

    The following example shows how to add a class method dynamically to a Python class.

    Open Compiler

    classCloth:pass# class method@classmethoddefbrandName(cls):print("Name of the brand is Raymond")# adding dynamicallysetattr(Cloth,"brand_name", brandName)
    newObj = Cloth()
    newObj.brand_name()

    When we execute the above code, it will show the following output −

    Name of the brand is Raymond
    

    Dynamically Delete Class Methods

    The Python del operator is used to delete a class method dynamically. If you try to access the deleted method, the code will raise AttributeError.

    Example

    In the below example, we are deleting the class method named “brandName” using del operator.

    Open Compiler

    classCloth:# class method@classmethoddefbrandName(cls):print("Name of the brand is Raymond")# deleting dynamicallydel Cloth.brandName
    print("Method deleted")

    On executing the above code, it will show the following output −

    Method deleted
  • Constants

    A constant in PHP is a name or an identifier for a simple value. A constant value cannot change during the execution of the PHP script.

    • By default, a PHP constant is case-sensitive.
    • By convention, constant identifiers are always uppercase.
    • A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscore.
    • There is no need to write a dollar sign ($) before a constant, however one has to use a dollar sign before a variable.

    Examples of Valid and Invalid Constant Names in PHP

    Here are some examples of valid and invalid constant names in PHP −

    // Valid constant namesdefine("ONE","first thing");define("TWO2","second thing");define("THREE_3","third thing");define("__THREE__","third value");// Invalid constant namesdefine("2TWO","second thing");

    Difference between Constants and Variables in PHP

    • Constants cannot be defined by simple assignment; they can only be defined using the define() function.
    • Constants may be defined and accessed anywhere without regard to variable scoping rules.
    • Once the Constants have been set, they may not be redefined or undefined.

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Defining a Named Constant

    The define() function in PHP library is used to define a named constant at runtime.

    define(string$const_name,mixed$value,bool$case=false):bool

    Parameters

    • const_name − The name of the constant.
    • value − The value of the constant. It can be a scalar value (int, float, string, bool, or null) or array values are also accepted.
    • case − If set to true, the constant will be defined case-insensitive. The default behavior is case-sensitive, i.e., CONSTANT and Constant represent different values.

    The define() function returns “true” on success and “false” on failure.

    Example 1

    The following example demonstrates how the define() function works −

    Open Compiler

    <?php  
       define("CONSTANT", "Hello world.");
    
       echo CONSTANT; 
       // echo Constant; 
    ?>

    The first echo statement outputs the value of CONSTANT. You will get the following output −

    Hello world.
    

    But, when you uncomment the second echo statement, it will display the following error −

    Fatal error: Uncaught Error: Undefined constant "Constant" in hello.php: on line 5
    

    If you set the case parameter to False, PHP doesn’t differentiate upper and lowercase constants.

    Example 2

    You can also use an array as the value of a constant. Take a look at the following example −

    Open Compiler

    <?php  
       define(
    
      $name="LANGS", 
      $value=array('PHP', 'Java', 'Python')
    ); var_dump(LANGS); ?>

    It will produce the following output −

    array(3) {
      [0]=>
      string(3) "PHP"
      [1]=>
      string(4) "Java"
      [2]=>
      string(6) "Python"
    }
    

    Using the constant() Function

    The echo statement outputs the value of the defined constant. You can also use the constant() function. It returns the value of the constant indicated by name.

    constant(string$name):mixed

    The constant() function is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

    Open Compiler

    <?php
       define("MINSIZE", 50);
    
       echo MINSIZE;
       echo PHP_EOL;
       echo constant("MINSIZE");	// same thing as the previous line
    ?>

    It will produce the following output −

    50
    50
    

    Using the defined() Function

    The PHP library provides a defined() function that checks whether a given named constant exists. Take a look at the following example −

    Open Compiler

    <?php
       define('MAX', 100);
    
       if (defined('MAX')) {
    
      echo MAX;
    } ?>

    It will produce the following output −

    100
    

    PHP also has a function called “get_defined_constants()” that returns an associative array of all the defined constants and their values.

  • $ and $$ Variables

    We know that PHP uses the convention of prefixing the variable names by the “$” symbol. PHP also has the provision of declaring dynamic variables by prefixing two dollar symbols ($$) to the name. A variable variable (or a dynamic variable) can be set and used dynamically.

    The declaration of a normal variable is like this −

    $a='good';

    A dynamic variable takes the value of a normal variable and treats that as the name of the variable. In the above example, “good” can be used as the name of a variable by using two dollar signs “$$” −

    $$a='morning';

    We now have two variables: “$a” with contents “good” and “$$a” with contents “morning”. As a result, the following echo statements will produce the same output −

    echo"$a {$$a}";echo"$a $good";

    Both produce the same output −

    good morning
    

    Example 1

    Take a look at this following example −

    Open Compiler

    <?php  
       $a = 'good';
       $$a = 'morning';
    
       echo "$a {$$a}\n";
       echo "$a $good";
    ?>

    It will produce the following output −

    good morning
    good morning
    

    Example 2

    Let’s take a look at another example −

    Open Compiler

    <?php  
       $x = "foo";  
       $$x = "bar";  
       echo "Value of x = " .$x . "\n";  
       echo 'Value of $$x = ' . $$x . "\n";  
       echo 'Value of foo = ' . $foo;  
    ?>

    Here, you will get the following output −

    Value of x = foo
    Value of $$x = bar
    Value of foo = bar
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Using Multiple “$” Symbols

    Note that the use of “$” symbol is not restricted to two. Any number of dollar symbols can be prefixed.

    Suppose there is a variable “$x” with “a” as its value. Next, we define $$x=’as’, then “$$x” as well as “$a” will have the same value. Similarly, the statement $$$x=’and’ effectively declares a “$as” variable whose value is ‘and’.

    Example

    Here is a complete example that shows the use of multiple “$” symbols.

    Open Compiler

    <?php  
       $php = "a";
       $lang = "php";
       $World = "lang";
       $Hello = "World";
       $a = "Hello";
       echo '$a= ' . $a;
       echo "\n";
       echo '$$a= ' . $$a;
       echo "\n";
       echo '$$$a= ' . $$$a;
       echo "\n";
       echo '$$$$a= ' . $$$$a;
       echo "\n";
       echo '$$$$$a= ' . $$$$$a;
    ?>

    When you run this code, it will produce the following output −

    $a= Hello
    $$a= World
    $$$a= lang
    $$$$a= php
    $$$$$a= a
    

    Using Dynamic Variables with Arrays

    Using dynamic variables with arrays may lead to certain ambiguous situations. With an array “a”, if you write $$a[1], then the parser needs to know if you are refering to “$a[1]” as a variable or if you want “$$a” as the variable and then the [1] index from that variable.

    To resolve this ambiguity, use ${$a[1]} for the first case and ${$a}[1] for the second.

    Example

    Take a look at the following example −

    Open Compiler

    <?php  
       $vars = array("hw", "os", "lang");
       $var_hw="Intel";
       $var_lang="PHP";
       $var_os="Linux";
    
       foreach ($vars as $var)
    
      echo ${"var_$var"} . "\n";
    print "$var_hw\n$var_os\n$var_lang"; ?>

    It will produce the following output −

    Intel
    Linux
    PHP
    Intel
    Linux
    PHP
    

    It may be noted that this technique cannot be used with PHP’s Superglobal arrays (Several predefined variables in PHP are “superglobals”, which means they are available in all scopes throughout a script) within functions or class methods. The variable “$this” is a special variable in PHP and it cannot be referenced dynamically.

  • Class Attributes

    The properties or variables defined inside a class are called as Attributes. An attribute provides information about the type of data a class contains. There are two types of attributes in Python namely instance attribute and class attribute.

    The instance attribute is defined within the constructor of a Python class and is unique to each instance of the class. And, a class attribute is declared and initialized outside the constructor of the class.

    Class Attributes (Variables)

    Class attributes are those variables that belong to a class and whose value is shared among all the instances of that class. A class attribute remains the same for every instance of the class.

    Class attributes are defined in the class but outside any method. They cannot be initialized inside __init__() constructor. They can be accessed by the name of the class in addition to the object. In other words, a class attribute is available to the class as well as its object.

    Accessing Class Attributes

    The object name followed by dot notation (.) is used to access class attributes.

    Example

    The below example demonstrates how to access the attributes of a Python class.

    Open Compiler

    classEmployee:
       name ="Bhavesh Aggarwal"
       age ="30"# instance of the class
    emp = Employee()# accessing class attributesprint("Name of the Employee:", emp.name)print("Age of the Employee:", emp.age)

    Output

    Name of the Employee: Bhavesh Aggarwal
    Age of the Employee: 30
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Modifying Class Attributes

    To modify the value of a class attribute, we simply need to assign a new value to it using the class name followed by dot notation and attribute name.

    Example

    In the below example, we are initializing a class variable called empCount in Employee class. For each object declared, the __init__() method is automatically called. This method initializes the instance variables as well as increments the empCount by 1.

    Open Compiler

    classEmployee:# class attribute    
       empCount =0def__init__(self, name, age):
    
      self.__name = name
      self.__age = age
      # modifying class attribute
      Employee.empCount +=1print("Name:", self.__name,", Age: ", self.__age)# accessing class attributeprint("Employee Count:", Employee.empCount)
    e1 = Employee("Bhavana",24)print() e2 = Employee("Rajesh",26)

    Output

    We have declared two objects. Every time, the empCount increments by 1.

    Name: Bhavana , Age:  24
    Employee Count: 1
    
    Name: Rajesh , Age:  26
    Employee Count: 2
    

    Significance of Class Attributes

    The class attributes are important because of the following reasons −

    • They are used to define those properties of a class that should have the same value for every object of that class.
    • Class attributes can be used to set default values for objects.
    • This is also useful in creating singletons. They are objects that are instantiated only once and used in different parts of the code.

    Built-In Class Attributes

    Every Python class keeps the following built-in attributes and they can be accessed using the dot operator like any other attribute −

    • __dict__ − Dictionary containing the class’s namespace.
    • __doc__ − Class documentation string or none, if undefined.
    • __name__ − Class name.
    • __module__ − Module name in which the class is defined. This attribute is “__main__” in interactive mode.
    • __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

    Access Built-In Class Attributes

    To access built-in class attributes in Python, we use the class name followed by a dot (.) and then attribute name.

    Example

    For the Employee class, we are trying to access all the built-in class attributes −

    Open Compiler

    classEmployee:def__init__(self, name="Bhavana", age=24):
    
      self.name = name
      self.age = age
    defdisplayEmployee(self):print("Name : ", self.name,", age: ", self.age)print("Employee.__doc__:", Employee.__doc__)print("Employee.__name__:", Employee.__name__)print("Employee.__module__:", Employee.__module__)print("Employee.__bases__:", Employee.__bases__)print("Employee.__dict__:", Employee.__dict__ )

    Output

    It will produce the following output −

    Employee.__doc__: None
    Employee.__name__: Employee
    Employee.__module__: __main__
    Employee.__bases__: (<class 'object'>,)
    Employee.__dict__: {'__module__': '__main__', '__init__': <function Employee.__init__ at 0x0000022F866B8B80>, 'displayEmployee': <function Employee.displayEmployee at 0x0000022F866B9760>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, '__doc__': None}
    

    Instance Attributes

    As stated earlier, an instance attribute in Python is a variable that is specific to an individual object of a class. It is defined inside the __init__() method.

    The first parameter of this method is self and using this parameter the instance attributes are defined.

    Example

    In the following code, we are illustrating the working of instance attributes.

    Open Compiler

    classStudent:def__init__(self, name, grade):
    
      self.__name = name
      self.__grade = grade
      print("Name:", self.__name,", Grade:", self.__grade)# Creating instances 
    student1 = Student("Ram","B") student2 = Student("Shyam","C")

    Output

    On running the above code, it will produce the following output −

    Name: Ram , Grade: B
    Name: Shyam , Grade: C
    

    Instance Attributes Vs Class Attributes

    The below table shows the difference between instance attributes and class attributes −

    SNo.Instance AttributeClass Attribute
    1It is defined directly inside the __init__() function.It is defined inside the class but outside the __init__() function.
    2Instance attribute is accessed using the object name followed by dot notation.Class attributes can be accessed by both class name and object name.
    3The value of this attribute cannot be shared among other objects.Its value is shared among other objects of the class.
    4Changes made to the instance attribute affect only the object within which it is defined.Changes made to the class attribute affect all the objects of the given class.
  • var_dump() Function

    One of the built-in functions in PHP is the var_dump() function. This function displays structured information such as type and the value of one or more expressions given as arguments to this function.

    var_dump(mixed$value,mixed...$values):void

    This function returns all the public, private and protected properties of the objects in the output. The dump information about arrays and objects is properly indented to show the recursive structure.

    For the built-in integer, float and Boolean varibles, the var_dump() function shows the type and value of the argument variable.

    Example 1

    For example, here is an integer variable −

    Open Compiler

    <?php
       $x = 10;  
       var_dump ($x);
    ?>

    The dump information is as follows −

    int(10)
    

    Example 2

    Let’s see how it behaves for a float variable −

    Open Compiler

    <?php
       $x = 10.25;  
       var_dump ($x);
    ?>

    The var_dump() function returns the following output −

    float(10.25)
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Example 3

    If the expression is a Boolean value −

    Open Compiler

    <?php
       $x = true;  
       var_dump ($x);
    ?>

    It will produce the following output −

    bool(true)
    

    Example 4

    For a string variable, the var_dump() function returns the length of the string also.

    Open Compiler

    <?php
       $x = "Hello World"; 
       var_dump ($x);  
    ?>

    It will produce the following output −

    string(11) "Hello World"
    

    Here we can use the <pre> HTML tag that dislays preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both the spaces and the line breaks.

    Open Compiler

    <?php
       echo "<pre>";
       $x = "Hello World"; 
       var_dump ($x);  
       echo "</pre>"
    ?>

    It will produce the following output −

    string(11) "Hello World"
    

    Example 5 – Studying the Array Structure Using var_dump()

    The var_dump() function is useful to study the array structure. In the following example, we have an array with one of the elements of the array being another array. In other words, we have a nested array situation.

    Open Compiler

    <?php
       $x = array("Hello", false, 99.99, array(10, 20,30));
       var_dump ($x);
    ?>

    It will produce the following output −

    array(4) {
      [0]=>
      string(5) "Hello"
      [1]=>
      bool(false)
      [2]=>
      float(99.99)
      [3]=>
      array(3) {
    
    &#91;0]=&gt;
    int(10)
    &#91;1]=&gt;
    int(20)
    &#91;2]=&gt;
    int(30)
    } }

    Example 6

    Since “$x” is an indexed array in the previous example, the index starting with “0” along with its value is dumped. In case the array is an associate array, the key-value pair information is dumped.

    Open Compiler

    <?php
       $x = array(
    
      "Hello", false, 99.99, 
      array(1=&gt;10, 2=&gt;20,3=&gt;30)
    ); var_dump($x); ?>

    Here, you will get the following output −

    array(4) {
      [0]=>
      string(5) "Hello"
      [1]=>
      bool(false)
      [2]=>
      float(99.99)
      [3]=>
      array(3) {
    
    &#91;1]=&gt;
    int(10)
    &#91;2]=&gt;
    int(20)
    &#91;3]=&gt;
    int(30)
    } }

    When you use var_dump() to show array value, there is no need of using the end tag ” </pre> “.

    Example 7

    The var_dump() function can als reveal the properties of an object representing a class. In the following example, we have declared a Point class with two private properties “x” and “y”. The class constructor initializes the object “p” with the parameters passed to it.

    The var_dump() function provides the information about the object properties and their corrcponding values.

    Open Compiler

    <?php  
       class Point {
    
      private int $x;
      private int $y;
      public function __construct(int $x, int $y = 0) {
         $this-&gt;x = $x;
         $this-&gt;y = $y;
      }
    } $p = new Point(4, 5); var_dump($p) ?>

    It will produce the following output −

    object(Point)#1 (2) {
      ["x":"Point":private]=>
      int(4)
      ["y":"Point":private]=>
      int(5)
    }
    

    There is a similar built-in function for producing dump in PHP, named as get_defined_vars().

    var_dump(get_defined_vars());

    It will dump all the defined variables to the browser.

  • Classes and Objects

    Python is an object-oriented programming language, which means that it is based on principle of OOP concept. The entities used within a Python program is an object of one or another class. For instance, numbers, strings, lists, dictionaries, and other similar entities of a program are objects of the corresponding built-in class.

    In Python, a class named Object is the base or parent class for all the classes, built-in as well as user defined.

    What is a Class in Python?

    In Python, a class is a user defined entity (data types) that defines the type of data an object can contain and the actions it can perform. It is used as a template for creating objects. For instance, if we want to define a class for Smartphone in a Python program, we can use the type of data like RAM, ROM, screen-size and actions like call and message.

    Creating Classes in Python

    The class keyword is used to create a new class in Python. The name of the class immediately follows the keyword class followed by a colon as shown below −

    classClassName:'Optional class documentation string'
       class_suite
    
    • The class has a documentation string, which can be accessed via ClassName.__doc__.
    • The class_suite consists of all the component statements defining class members, data attributes and functions.

    Example

    Following is the example of a simple Python class −

    classEmployee:'Common base class for all employees'
       empCount =0def__init__(self, name, salary):
    
      self.name = name
      self.salary = salary
      Employee.empCount +=1defdisplayCount(self):print"Total Employee %d"% Employee.empCount
    defdisplayEmployee(self):print"Name : ", self.name,", Salary: ", self.salary
    • The variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.
    • The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.
    • You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    What is an Object?

    An object is refered to as an instance of a given Python class. Each object has its own attributes and methods, which are defined by its class.

    When a class is created, it only describes the structure of obejcts. The memory is allocated when an object is instantiated from a class.

    class object in python

    In the above figure, Vehicle is the class name and Car, Bus and SUV are its objects.

    Creating Objects of Classes in Python

    To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

    # This would create first object of Employee class
    emp1 = Employee("Zara",2000)# This would create second object of Employee class
    emp2 = Employee("Manni",5000)

    Accessing Attributes of Objects in Python

    You access the object’s attributes using the dot operator with object. Class variable would be accessed using class name as follows −

    emp1.displayEmployee()
    emp2.displayEmployee()print("Total Employee %d"% Employee.empCount)

    Now, putting all the concepts together −

    Open Compiler

    classEmployee:"Common base class for all employees"
       empCount =0def__init__(self, name, salary):
    
      self.name = name
      self.salary = salary
      Employee.empCount +=1defdisplayCount(self):print("Total Employee %d"% Employee.empCount)defdisplayEmployee(self):print("Name : ", self.name,", Salary: ", self.salary)# This would create first object of Employee class
    emp1 = Employee("Zara",2000)# This would create second object of Employee class emp2 = Employee("Manni",5000) emp1.displayEmployee() emp2.displayEmployee()print("Total Employee %d"% Employee.empCount)

    When the above code is executed, it produces the following result −

    Name :  Zara , Salary:  2000
    Name :  Manni , Salary:  5000
    Total Employee 2
    

    You can add, remove, or modify attributes of classes and objects at any time −

    # Add an 'age' attribute
    emp1.age =7# Modify 'age' attribute
    emp1.age =8# Delete 'age' attributedel emp1.age  
    

    Instead of using the normal statements to access attributes, you can also use the following functions −

    • getattr(obj, name[, default]) − to access the attribute of object.
    • hasattr(obj,name) − to check if an attribute exists or not.
    • setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
    • delattr(obj, name) − to delete an attribute.
    # Returns true if 'age' attribute existshasattr(emp1,'age')# Returns value of 'age' attributegetattr(emp1,'age')# Set attribute 'age' at 8setattr(emp1,'age',8)# Delete attribute 'age'delattr(empl,'age')

    Built-In Class Attributes in Python

    Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −

    SNo.Attributes & Description
    1__dict__Dictionary containing the class’s namespace.
    2__doc__Class documentation string or none, if undefined.
    3__name__Class name
    4__module__Module name in which the class is defined. This attribute is “__main__” in interactive mode.
    5__bases__A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

    Example

    For the above Employee class, let us try to access its attributes −

    Open Compiler

    classEmployee:'Common base class for all employees'
       empCount =0def__init__(self, name, salary):
    
      self.name = name
      self.salary = salary
      Employee.empCount +=1defdisplayCount(self):print("Total Employee %d"% Employee.empCount)defdisplayEmployee(self):print("Name : ", self.name,", Salary: ", self.salary)print("Employee.__doc__:", Employee.__doc__)print("Employee.__name__:", Employee.__name__)print("Employee.__module__:", Employee.__module__)print("Employee.__bases__:", Employee.__bases__)print("Employee.__dict__:", Employee.__dict__)</code></pre>

    When the above code is executed, it produces the following result −

    Employee.__doc__: Common base class for all employees
    Employee.__name__: Employee
    Employee.__module__: __main__
    Employee.__bases__: ()
    Employee.__dict__: {'__module__': '__main__', 'displayCount':
    <function displayCount at 0xb7c84994>, 'empCount': 2, 
    'displayEmployee': <function displayEmployee at 0xb7c8441c>, 
    '__doc__': 'Common base class for all employees', 
    '__init__': <function __init__ at 0xb7c846bc>}
    

    Built-in Class of Python datatypes

    As mentioned earlier, Python follows object-oriented programming paradigm. Entities like strings, lists and data types belongs to one or another built-in class.

    If we want to see which data type belongs to which built-in class, we can use the Python type() function. This function accepts a data type and returns its corresponding class.

    Example

    The below example demonstrates how to check built-in class of a given data type.

    Open Compiler

    num =20print(type(num))
    num1 =55.50print(type(num1))
    s ="TutorialsPoint"print(type(s))
    dct ={'a':1,'b':2,'c':3}print(type(dct))defSayHello():print("Hello World")returnprint(type(SayHello))

    When you execute this code, it will display the corresponding classes of Python data types −

    <class 'int'>
    <class 'float'>
    <class 'str'>
    <class 'dict'>
    <class 'function'>
    

    Garbage Collection(Destroying Objects) in Python

    Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.

    Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

    An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

    # Create object <40>
    a =40# Increase ref. count  of <40> 
    b = a       
    # Increase ref. count  of <40> 
    c =[b]# Decrease ref. count  of <40>del a       
    # Decrease ref. count  of <40>
    b =100# Decrease ref. count  of <40>
    c[0]=-1

    You normally will not notice when the garbage collector destroys an unused instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.

    Example

    The __del__() destructor prints the class name of an instance that is about to be destroyed as shown in the below code block −

    Open Compiler

    classPoint:def__init__( self, x=0, y=0):
    
      self.x = x
      self.y = y
    def__del__(self):
      class_name = self.__class__.__name__
      print(class_name,"destroyed")
    pt1 = Point() pt2 = pt1 pt3 = pt1 # prints the ids of the obejctsprint(id(pt1),id(pt2),id(pt3))del pt1 del pt2 del pt3

    On executing, the above code will produces following result −

    135007479444176 135007479444176 135007479444176
    Point destroyed
    

    Data Hiding in Python

    An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.

    Example

    Open Compiler

    classJustCounter:
       __secretCount =0defcount(self):
    
      self.__secretCount +=1print self.__secretCount
    counter = JustCounter() counter.count() counter.count()print counter.__secretCount

    When the above code is executed, it produces the following result −

    1
    2
    ERROR!
    Traceback (most recent call last):
      File <main.py>", line 11, in <module>
    AttributeError: 'JustCounter' object has no attribute '__secretCount'
    

    Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −

    print(counter._JustCounter__secretCount)

    When the above code is executed, it produces the following result −

    1
    2
    2
  • Echo/Print

    In PHP, both echo and print statements are used to render the output either on the browser or the PHP console. Both of them are not functions but they are language constructs. Hence, parentheses should not be used with either of them.

    The “echo” Statement in PHP

    The echo statement is used with following syntax −

    echo(string...$expressions):void

    The echo statement outputs one or more expressions, with no additional newlines or spaces.

    Example

    Here is an example of how the echo statement works in PHP −

    Open Compiler

    <?php
       $name = "Rajesh";
       echo "Hello " . $name . " How are you?"
    ?>

    It will produce the following output −

    Hello Rajesh How are you?
    

    Since a double quoted string is similar to a single quoted string in PHP, the following statement produces the same output.

    echo'Hello '.$name.' How are you?';

    Example

    A double quoted string outputs the value of the variable. Hence, the following statement inserts the value of “$name” variable before printing the output.

    Open Compiler

    <?php
       $name = "Rajesh";
       echo "Hello $name How are you?";
    ?>

    It will produce the following output −

    Hello Rajesh How are you?
    

    Example

    But, a single-quoted string will output “$name” as it is.

    Open Compiler

    <?php
       $name = "Rajesh";
       echo 'Hello $name How are you?';
    ?>

    It will produce the following output −

    Hello $name How are you?
    

    A string passed to an echo statement can either be passed individually as multiple arguments or concatenated together and passed as a single argument. So, both the following statements are valid −

    echo'Hello ','how ','are ','you?',"\n";echo'Hello '.'how '.'are '.'you?'."\n";

    Example

    Note that output of the two successive echo statements will be rendered in the same line if the newline character is not used. Take a look at the following example −

    Open Compiler

    <?php
       echo "hello";
       echo "world";
    ?>

    It will produce the following output −

    helloworld
    

    The “print” Statement in PHP

    The print statement is similar to echo, but it outputs an expression.

    print(string$expression):int

    Like echo, print is also a language construct. Its argument is an expression but it is not put in parentheses.

    The major difference is that the print statement in PHP accepts a single argument only and always returns 1.

    Example

    Take a look at this following example −

    Open Compiler

    <?php
       $name = "Rajesh";
    
       print "Hello " . $name . " How are you?\n";
       print "Hello $name How are you?";
    ?>

    It will produce the following output −

    Hello Rajesh How are you?
    Hello Rajesh How are you?
    

    Output Multiline Strings Using Print/Echo

    Both echo and print statements can output multiline strings spanning over more than one lines in the editor. Take a look at the following example −

    Open Compiler

    <?php
       print "
       Multi-line
       string can be output  
       by echo as well as 
       print statement in PHP
       ";  
    ?>

    It will produce the following output −

    Multi-line
    string can be output
    by echo as well as
    print statement in PHP
    

    The output will remain the same if we replace print with echo.

  • Variables

    A variable in PHP is a named memory location that holds data belonging to one of the data types.

    • PHP uses the convention of prefixing a dollar sign ($) to the name of a variable.
    • Variable names in PHP are case-sensitive.
    • Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
    • As per the naming convention, “$name”, “$rate_of_int”, “$Age”, “$mark1” are examples of valid variable names in PHP.
    • Invalid variable names: “name” (not having $ prefix), “$rate of int” (whitespace not allowed), “$Age#1” (invalid character #), “$11” (name not starting with alphabet).

    Variables are assigned with the “=” operator, with the variable on the left hand side and the expression to be evaluated on the right.

    No Need to Specify the Type of a Variable

    PHP is a dynamically typed language. There is no need to specify the type of a variable. On the contrary, the type of a variable is decided by the value assigned to it. The value of a variable is the value of its most recent assignment.

    Take a look at this following example −

    Open Compiler

    <?php
       $x = 10;
       echo "Data type of x: " . gettype($x) . "\n";
    
       $x = 10.55;
       echo "Data type of x now: " . gettype($x) . "";
    ?>

    It will produce the following output −

    Data type of x: integer
    Data type of x now: double
    

    Automatic Type Conversion of Variables

    PHP does a good job of automatically converting types from one to another when necessary. In the following code, PHP converts a string variable “y” to “int” to perform addition with another integer variable and print 30 as the result.

    Take a look at this following example −

    Open Compiler

    <?php
       $x = 10;
       $y = "20";
    
       echo "x + y is: ", $x+$y;
    ?>

    It will produce the following output −

    x + y is: 30
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Variables are Assigned by Value

    In PHP, variables are always assigned by value. If an expression is assigned to a variable, the value of the original expression is copied into it. If the value of any of the variables in the expression changes after the assignment, it doesn’t have any effect on the assigned value.

    Open Compiler

    <?php
       $x = 10;
       $y = 20;
       $z = $x+$y;
       echo "(before) z = ". $z . "\n";
    
       $y=5;
       echo "(after) z = ". $z . "";
    ?>

    It will produce the following output −

    (before) z = 30
    (after) z = 30
    

    Assigning Values to PHP Variables by Reference

    You can also use the way to assign values to PHP variables by reference. In this case, the new variable simply references or becomes an alias for or points to the original variable. Changes to the new variable affect the original and vice versa.

    To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable).

    Take a look at this following example −

    Open Compiler

    <?php
       $x = 10;
       $y = &$x;
       $z = $x+$y;
       echo "x=". $x . " y=" . $y . " z = ". $z . "\n";
    
       $y=20;
       $z = $x+$y;
       echo "x=". $x . " y=" . $y . " z = ". $z . "";
    ?>

    It will produce the following output −

    x=10 y=10 z = 20
    x=20 y=20 z = 40
    

    Variable Scope

    Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −

    • Local Variables
    • Global Variables
    • Static Variables
    • Function Parameters

    Variable Naming

    Rules for naming a variable is −

    • Variable names must begin with a letter or underscore character.
    • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc

    There is no size limit for variables.

  • Comments

    A comment in any computer program (such as a PHP program) is a certain explanatory text that is ignored by the language compiler/interpreter. Its purpose is to help the user understand the logic used in the program algorithm.

    Although placing comments in the code is not essential, it is a highly recommended practice. The comments also serve as program documentation. Comments are also useful when the code needs to be debugged and modified.

    There are two commenting formats in PHP −

    • Single-line Comments
    • Multi-line Comments

    Single-line Comments

    They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for inserting a single-line comment in a program.

    Single-line Comments Using “#”

    A line in PHP code starting with the “#” symbol is treated as a single-line comment.

    Open Compiler

    <?php
       # Single line comment starting with # symbol
       echo 'Hello World';
    ?>

    Single-line Comments Using “//”

    PHP also supports C style of single-line comments with “//” symbol. A line starting with double oblique symbol is treated as a comment.

    Open Compiler

    <?php
       // Single line comment starting with // symbol
       echo 'Hello World';
    ?>

    A comment that starts with the symbol “#” or “//” need not be closed. The effect of these symbols last till the end of the physical line.

    In other words, the PHP parser will treat the next line as a PHP statement and not as a comment even if there is no closing comment marker.

    Multi-line Comments

    Multi-line comments are generally used to provide pseudocode algorithms and more detailed explanations when necessary.

    The multiline style of commenting is the same as in C. One or more lines embedded inside the “/*” and “*/” symbols are treated as a comment.

    Example of Multi-line Comment in PHP

    Here is the example of a multi-line comment.

    Open Compiler

    <?php
    
       /* This is a multiline comment example
       program to add two numbers
       Variables used - $x for first number, 
       $y for second number */
       
       $x=10;
       $y=20;
       print "Total = ". $x+$y;
    ?>

    Note that you can put even a single line inside the “/* .. */” symbols. However, if there is a “/*” symbol in the program, it must have a closing end-of comment marker “*/”. If not, an error will be displayed as follows −

    PHP Parse error:  Unterminated comment starting line 3 in /home/cg/root/65ded9eeb52fc/main.php on line 3