Overloading

  • Overloading in PHP provides means to dynamically create properties and methods.
  • These dynamic entities are processed via magic methods, one can establish in a class for various action types.
  • All overloading methods must be defined as Public.
  • After creating object for a class, we can access set of entities that are properties or methods not defined within the scope of the class.
  • Such entities are said to be overloaded properties or methods, and the process is called as overloading.
  • For working with these overloaded properties or functions, PHP magic methods are used.
  • Most of the magic methods will be triggered in object context except __callStatic() method which is used in static context.
OVERLOADING

Property overloading

  • PHP property overloading allows us to create dynamic properties in object context.
  • For creating those properties no separate line of code is needed.
  • A property which is associated with class instance, and not declared within the scope of the class, is considered as overloaded property.

Some of the magic methods which is useful for property overloading.

  • __set(): It is triggered while initializing overloaded properties.
  • __get(): It is utilized for reading data from inaccessible Properties.
  • __isset(): This magic method is invoked when we check overloaded properties with isset() function.
  • __unset(): This function will be invoked on using PHP unset() for overloaded properties.

Interface

  • An interface is similar to a class except that it cannot contain code.
  • An interface can define method names and arguments, but not the contents of the methods.
  • Any classes implementing an interface must implement all methods defined by the interface.
  • A class can implement multiple interfaces.
  • An interface is declared using the “interface” keyword.
  • Interfaces can’t maintain Non-abstract methods.

Example 1

<?php  
    interface a  
    {  
        public function dis1();  
    }  
    interface b  
    {  
        public function dis2();  
    }  
  
class demo implements a,b  
{  
    public function dis1()  
    {  
        echo "method 1...";  
    }  
    public function dis2()  
    {  
        echo "method2...";  
    }  
}  
$obj= new demo();  
$obj->dis1();  
$obj->dis2();  
  
?>  

Output:

method 1…method 2…

Example 2

  

<?php  
    interface i1  
    {  
        public function fun1();  
    }  
    interface i2  
    {  
        public function fun2();  
    }  
class cls1 implements i1,i2  
{  
    function fun1()  
    {  
        echo "protutorials";  
    }  
    function fun2()  
    {  
        echo "tech";  
    }  
}  
$obj= new cls1();  
$obj->fun1();  
$obj->fun2();  
  
?>

Output:

protutorialstech

PHP functions

1. get_class: By using this, we can get the class name of an object.

Example 1

<?php  
    class cls1  
    {  
          
    }  
    $obj=new cls1();  
    echo get_class($obj);  
?>  

Output:

cls1

2. get_class_vars: It is used to get all variables of a class as Array elements.

Example 2

<?php  
    class cls1  
    {  
        var $x=100;  
        var $y=200;  
    }  
    print_r(get_class_vars("cls1"));  
?>  

Output:

Array([x] => 100[y]=>200)

3. get_class_methods: To get the all methods of a class as an array.

Example 3

<?php  
    class cls1  
    {  
        function fun1()  
        {  
        }  
        function fun2()  
        {  
        }  
    }  
    print_r(get_class_methods("cls1"));  
?>  

Output:

Array([0] => fun1[1] =>fun2 )

4. get_declare_classes: To get the all declare classes in current script along with predefined classes.

Example 4

<?php  
    class cls1  
    {  
      
    }  
    print_r(get_declared_classes());  
?>  

Output:

Some Helpful Functions in PHP to get the Information About Class and Object

5. get_object_vars: To get all variables of an object as an array.

Example 5

<?php  
    class cls1  
    {  
        var $x=100;  
        var $y=200;  
    }  
    $obj= new cls1();  
    print_r(get_object_vars($obj));  
?>  

Output:

Array([x] => 100[y]=>200)

6. class_exists: To check whether the specified class is existed or not.

Example 6

<?php  
    class cls1  
    {  
          
    }  
    echo class_exists("cls1");  
?>  

Output:

1

7. is_subclass_of: By using this function we can check whether the 1st class is subclass of 2nd class or not.

Example 7

<?php  
    class cls1  
    {  
          
    }  
    class cls2 extends cls1  
    {  
    }  
    echo is_subclass_of("cls2","cls1");  
?>  

Output:

1

8. method_exists: By using this function we can check whether the class method is existed or not.

Example 8

<?php  
    class cls1  
    {  
        function fun1()  
        {  
        }  
    }  
    echo method_exists("cls1","fun1");  
?>  

Output:

1

Final Keyword

  • In PHP, Final keyword is applicable to only class and class methods. We cannot declare as Final in PHP.
  • So if we declare class method as a Final then that method cannot be override by the child class.
  • Same as method if we declare class as a Final then that class cannot be extended any more.

Example 1

<?php  
      
    class base  
    {  
        final public function dis1()  
        {  
            echo "Base class..";  
        }     
    }  
    class derived extends base  
    {  
        public function dis1()  
        {  
            echo "derived class";  
        }  
    }  
    $obj = new derived();  
    $obj->dis1();  
  
?>  

Output:

Final Keyword

PHP Form Handling

We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST.

PHP Get Form

Get request is the default form request. The data passed through get request is visible on the URL browser so it is not secured. You can send limited amount of data through get request.

Let’s see a simple example to receive data from get request in PHP.

<form action="welcome.php" method="get">  
Name: <input type="text" name="name"/>  
<input type="submit" value="visit"/>  
</form>   

PHP Post Form

Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You can send large amount of data through post request.

Let’s see a simple example to receive data from post request in PHP.

<form action="login.php" method="post">   
<table>   
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>  
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>   
<tr><td colspan="2"><input type="submit" value="login"/>  </td></tr>  
</table>  
</form>  
<?php  
$name=$_POST["name"];//receiving name field value in $name variable  
$password=$_POST["password"];//receiving password field value in $password variable  
  
echo "Welcome: $name, your password is: $password";  
?>  

Output:

php form
php login form handling

JavaScript Document Object

JavaScript Document object is an object that provides access to all HTML elements of a document. When an HTML document is loaded into a browser window, then it becomes a document object.

The document object stores the elements of an HTML document, such as HTML, HEAD, BODY, and other HTML tags as objects.

A document object is a child object of the Window object, which refers to the browser.

You can access a document object either using window.document property or using object directly.

See, What we can do with Document Object:

  • Suppose you have created a FORM in an HTML document using the FORM element and added some text fields and Buttons on the Form. On Submitting the Form you want to validate the input or display input on another page. In this situation, you can use a document object which is a child object of the window object. Using the document object, you can access the elements of the form and validate the Input.
  • The Document Object provides different collection elements, such as anchor and Links which helps you to count the number of specific elements on a form.
  • The Document Object also provides various properties such as URLbgcolor, etc. which will allow you to retrieve the details of a document and various methods such as open()close()write(), getElementById()getElementByName(), etc. which allow you to perform various tasks like opening an HTML document to display output and writing a text on Web Page.
  • The Document Object also allows you to create cookies for a webpage by providing a property named cookie. A cookie stores information about the user’s computer, which helps in accessing visited websites.

Now let’s explore document object methods and properties.

JavaScript Document Object Properties

As we know, a property of an object is the value associated with the object. The property is accessed by using the following notation:

objectName.propertyName

where objectName is the name of the object and propertyName is the name of its property.

Now we will show you the properties of document object in the table given below:

PropertiesDescription
cookiereturns a report that contains all the visible and unexpired cookies associated with the document
domainreturns the domain name of the server from which the document has originated
lastModifiedreturns the date on which document was last modified
documentModereturns the mode used by the browser to process the document
readyStatereturns the loading status of the document.
referrerreturns the URL of the documents referred to in an HTML document
titlereturns the name of the HTML document defined between the starting and ending tags of the TITLE element
URLreturns the full URL of the HTML document.

Let’s take an example, to see the document object properties in action:


JS Document Methods Example

Document Methods Example

    <script>
        // Open document
        document.open();
        // writing
        document.write("Hello" +"<br>");
        document.getElementById("demo").innerHTML = "Set by ID";
    </script>
</body>

JavaScript Document Object Methods

JavaScript Document object also provides various methods to access HTML elements.

Now we will show you some of the commonly used methods of the document object:

MethodsDescriptionSyntax
open()opens an HTML document to display the outputdocument.open(mimetype, replace)
close()closes an HTML documentdocument.close()
write()Writes HTML expressions or JavaScript code into an HTML documentdocument.write(exp1, exp2, ...)
writeln()write a new line character after each HTML expressions or JavaScript Codedocument.writeln(exp1, exp2, ...)
getElementById()returns the reference of first element of an HTML document with the specified id.document.getElementById(id)
getElementByName()returns the reference of an element with the specified namedocument.getElementsByName(name)
getElementsByTagName()returns all elements with the specified tagnamedocument.getElementsByTagName(tagname)

Now let’s take an example, to see the document object methods like open()write(), and getElementById() to explain their usage. See the below example:

It Will change

    <script>
        // Open document
        document.open();
        // writing
        document.write("Hello" +"<br>");
        document.getElementById("demo").innerHTML = "Set by ID";
    </script>
</body>

JavaScript Screen Object

JavaScript Screen is a built-in Interface (object type) that is used to fetch information related to the browser screen on which the current window is rendered.

It provides information about the dimensions of the display screen such as its height, width, color bits, etc.

Since the window object is at the top of the scope chain, the property window.screen gives the Screen object, but the screen object can be accessed without specifying the window too, in that case JavaScript automatically detects the browser window, which is created by JavaScript Runtime Engine.

Let’s take a simple example to see the working of the screen object.
JS Screen Object Example

JavaScript Screen Object

    <script>
        document.writeln("Total Height: " + screen.height +"<br>");
        document.writeln("Total Width: " + screen.width +"<br>");
    </script>
</body>

JavaScript Screen Object Properties

JavaScript Screen object includes some properties that are used to get browser screen information. A table of such properties is given below.

PropertyDescription
availHeightspecifies the height of screen, excluding the windows taskbar
availWidthspecifies the width of the screen, excluding the Windows taskbar
colorDepthspecifies the depth of color palette, in bits, to display images
heightspecifies the total height of the screen
pixelDepthspecifies the color Resolution, in bits per pixel, of the screen
widthspecifies the total width of the screen

The Screen object colorDepth property is the number of bits used to represent the color of a single pixel. It returns the bit depth of the color palette for displaying images.

JavaScript Screen Object Methods

There are no direct methods in the Screen method object.

Uses of Screen Object

The JavaScript Screen object can be used for improving the user experience by controlling the UI of the web app or website based on the screen size.

JavaScript Location Object

JavaScript Location is a built-in Interface (object type) which represents the location (URL) of the object to which it is attached. Both the Window object and the Document object have this property. The window objects location property gives us access to the browser window’s location whereas the document location property gives us the location object for a particular document.

It is used to fetch information of the current URL. The Location object allows you to navigate to another webpage as well.

Get Website Host name

    <script>
         var x = location.hostname;
        document.write(x);

    </script>
</body>

There are many different properties of the location object and many methods too.

JavaScript Location Object Properties

JavaScript Location Object has many properties using which we can access the various components of a webpage’s URL and even change it.

Here are some commonly used properties for the location object:

PropertyDescription
hrefRepresents a string specifying the entire URL, for instance
protocolRepresents a String at the begining of a URL to the first colon(:),which specifies the Method of access to the URL , for instance http: or https:
hostRepresents a String consisting of hostname and port Strings,for instance:- http://www.javascriptstudytonight.com:80
hostnameRepresents the server name, subdomain, and domain name (or IP address)of a URL, for instance http://www.javascriptstudytonight.com
portRepresents a string specifying the communication port that the server uses, for instance 80
pathnameRepresents a String Portion of a URL, specifying how a particular resource can be accessed, for instance: order.cgi
searchRepresents a string beginning with a question mark that specifies any query information in an HTTP URL, for instance batch=1
hashRepresents a string beginning with a hash(#), which specifies an anchor name in an HTTP URL, for instance #intro

Let’s take an example and get to know about the properties of Location object.

Location Properties

    <script>
        // Hostname
        let x = location.hostname;
        document.write(x +"<br>");
        // href
        x = location.href;
        document.write(x +"<br>");
        // protocol
        x = location.protocol;
        document.write(x +"<br>");
        // host
        x = location.host;
        document.write(x +"<br>");
        // pathname
        x = location.pathname;
        document.write(x +"<br>");
    </script>
</body>

Now let’s see the methods of the location object.

JavaScript Location Object Methods

Location Object methods refers to the functions created inside the location interface which can be used to perform various operations on the URL like reload it, change it, etc.

MethodDescription
assign()Loads a new Document in the Browser
reload()Reloads the current document that is contained in location.href property.
replace()Replaces the current document with the specified new one. In addition, you cannot navigate back to the previous document using the Browser’s back button.

To load a new document, We can use the assign() method of Location object. But in this example, we have used the href property and the replace() methods too. They all can be used to load a document.

Location Methods example

    <button onclick="load1()">visit studytonight.com</button>
    <button onclick="load2()">visit studytonight.com</button>
    <button onclick="load3()">visit studytonight.com</button>

    <script>
        // assign method
        function load1(){
            location.assign("https://www.studytonight.com");
        }

        // href
        function load2(){
            location.href="https://www.studytonight.com";
        }

        // replace()
        function load3(){
            location.replace("https://www.studytonight.com");
        }

    </script>
</body>

JavaScript Navigator Object

JavaScript Navigator Object is used to fetch information related to the browser(useragent), like the browser name, browser version, operating system information, etc.

JavaScript Navigator object is also a property of the JavaScript Window object and can be accessed using the read only property window.navigator for the current browser window.

In JavaScript, the Navigator Object includes some properties and methods which help us to navigate from one element to another.

Navigator Object Properties

The properties of the navigator object are the variables created inside the Navigator Object.

We can access Navigator Object Property as: navigator.propertyname where propertyname is the name of property.

PropertiesDescription
appcodenamespecifies the code name of the browser (experimental property – can return incorrect value)
appnamespecifies the name of the browser (experimental property – can return incorrect value)
appversionspecifies the version of browser being used (experimental property – can return incorrect value)
cookieEnabledspecifies whether cookies are enabled or not in the browser
platformcontains a string indicating the machine type for which the browser was compiled.
useragentcontains a string representing the value of user-agent header sent by the client to server in HTTP protocol
geolocationreturns object of GeoLocation which can be used to get the location information of the device.
onLinespecifies whether the browser is online or not.
languagereturns a string with the preferred browser language, for example, en-US for English.
languagesreturns a string with all the languages supported by the browser in order of user preference.

There are some more expreimental properties available in the Navigator object, but the ones mentioned above are most commonly used properties.

Navigator Object Example

    <script>
        let appc =  navigator.appCodeName;
        let appn =  navigator.appName;
        let appv =  navigator.appVersion;
        let appco = navigator.cookieEnabled;
        let lan   = navigator.language;
        let onl = navigator.onLine;
        let pla = navigator.platform;
        let usra = navigator.userAgent;

        document.write(appc +"<br>");
        document.write(appn +"<br>");
        document.write(appv +"<br>");
        document.write(appco +"<br>");
        document.write(lan +"<br>");
        document.write(onl +"<br>");
        document.write(pla +"<br>");
        document.write(usra +"<br>");
    </script>

</body>

Navigator Object Methods

The Navigator object doesn’t have many standardised methods, most of the methods available are experimental.

Method NameDescription
registerProtocolHandler()allows websites to register themselves as protocol handler so that they are allowed to open some standard URL schemes like mailto:tel:sms:, etc,
share()used to utilize the native support of sharing available in browser.
sendBeacon()used to send a small data packet from the client to the server
vibrate()if supported, this can be used to make the device vibrate, if not supported, nothing happens. This is useful in mobile browsers.

Use of Navigator Object:

The navigator object can be used for multiple specific usecases which can help you make your website better, like:

  1. Making you web app or website more compatible with different browsers by writing specific code for different browsers to resolve compatibility issues.
  2. You can check if the browser is online or not, to show some message if the browser is disconnected from internet.
  3. You can use the location information of the user to show location specific content.
  4. You can set the preferred language as the website language if you support multiple languages on your website.

All the points mentioned above can improve the user experience of your website multifold.

JavaScript History Object

JavaScript History is a built-in Interface (object type) which is used to access the browser window session history. It contains the list of URLs visted by a user in a particular browser window, tab or frame, represented by the window object.

The history object is a property of the JavaScript window object, and can be accessed through the window.history property, and is used to access the session history for that window object.

It provides useful methods and properties that let us navigate back and forth through the window’s session history.

Let’s take an example to see how this works to understand it better.

JavaScript History Object Example

The History object’s back() method is used to go back to the previous URL accessed in the browser window, in the history list.

It is same as clicking the “Back button” in your browser.

<button onclick="goBack()">Go Back</button>

<script>
	function goback(){
	    window.history.back();
	}
</script>

Similarly, we can use the history object’s forward() method to load the next URL in the history list. If next URL is not present, it does nothing.

It is same as clicking the “Forward button” in your browser.

<button onclick="goforward()">Go Forward</button>

<script>
	function goforward(){
	    window.history.forward();
	}
</script>

Apart from the back() and forward(), JavaScript history object provides more methods like go()which can be used to jump to any specific URL present in the history object.

To move to any specific page, we can use the go() method, it takes an integer argument that works as an index value for history URL list. See the below example:

<script>
    // move to one page backward
	window.history.go(-1);

    // move to two page backward
    window.history.go(-2);

    // move to one page forward
    window.history.go(1);

    // move to two page forward
    window.history.go(2);
</script>

We can also use the go() method of history object to refresh the current page. In the example below, we have called the go() method two times and it works the same in the both scenario. We can call it anytime when we want to refresh/reload the current page.

<script>
// Refresh the page
        window.history.go(0);

        window.history.go();

</script>

JavaScript History Object Property

Following are the properties of the History object. The length property is used the most.

PropertiesDescription
lengthspecifies the number of elements contained in the object
scrollRestorationallows web applications to explicitly set default scroll restoration behavior on history navigation
staterepresents the state at the top of the history stack

Let’s take an example to get number of pages visited by a user in a browser window. We will use the length property that contains information for the visited pages.

JavaScript History Object Methods

JavaScript History object methods refer to the functions created inside the history object. These methods specify the actions related to the URLs visited in the Browser window’s current session.

MethodsDescription
back()specifies a method that loads the previous URL from the history list.
forward()specifies a method that loads the next URL from the history list.
go()specifies a method that loads a specific URL from the history list.
pushState()used to push the given data onto the session history stack with the specified title
replaceState()used to update the most recent entry on the history stack to the specified data, title, and, if provided, URL

We have explained each method with examples in the beginning of this tutorial itself.

In the next tutorial we will learn about the Navigator browser object.