Method overloading simple example in php

Introduction to Method Overloading in PHP

Method Overloading is one type of Overloading other than Property Overloading. It is to create one/many dynamic methods that are not created within that class scope/scopes. PHP method overloading concept also helps in triggering the magic methods which are dictated for the appropriate purpose. Apart from the property overloading concept, the PHP method’s overloading concept allows function call/calls on both the object and also the static context. Basically is one of the methods of OOPs.

Syntax:

Public _call [string $name1 , array $arguments1 ] : mixed
Public static _callStatic [string $name1 , array $arguments1 ] : mixed

How does Method Overloading work in PHP?

The Method Overloading works with the declaration inside the class by creating dynamic methods. It also works by triggering some magic methods for an appropriate purpose and it also calls function/function calls on both the static context and the object. Method Overloading concept is also fine with most of the other programming languages like c, java, etc.. Method Overloading concept is also called a static polymorphic concept.

There are some of the magic functions, they are:

  • _call[]: This call[] magic function will be triggered in order to invoke the overloaded method/methods which are in the object context.
  • _callStatic[]: This callstatic[] magic function will also be triggered in order to invoke the overloaded concepts/methods which are in the static context.

Examples of Method Overloading in PHP

Here are the examples of Method Overloading in PHP mention below

Example #1

The $name1 argument which is in the below PHP programming language is the name of the method which is to be called whereas $arguments are one of the enumerated arrays which contain the parameters/arguments which are used to pass to the $name ’ed method.

_call[] function used using 2 parameters $name1 and $arguments1. Implode[] function actually returns string from the array elements i.e., from the string/sentence. In Implode[separator, array], the separator is the optional parameter but it just a recommendation to use both of the parameters for backward compatibility. The specific type of separator in the separator parameter will insert separator to the words/strings which are present in the array parameter.

The Obj variable will create a new object called SPK. Obj-> will helps in order to access the methods and the properties of the object. Spk will execute from the static context whereas the obj will run from the object context.

Code:

Chủ Đề