PHP â Loop Types ”; Previous Next Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types. for − Loops through a block of code a specified number of times. foreach − Loops through a block of code for each element in an array. while − Loops through a block of code if and as long as a specified condition is true. do-while − Loops through a block of code once, and then repeats the loop as long as a special condition is true. In addition, we will also explain how the continue and break statements are used in PHP to control the execution of loops. PHP for Loop The for statement is used when you know how many times you want to execute a statement or a block of statements. Syntax for (initialization; condition; increment){ code to be executed; } The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i. Example The following example makes five iterations and changes the assigned value of two variables on each pass of the loop − <?php $a = 0; $b = 0; for( $i = 0; $i<5; $i++ ) { $a += 10; $b += 5; } echo (“At the end of the loop a = $a and b = $b” ); ?> It will produce the following output − At the end of the loop a = 50 and b = 25 PHP foreach Loop The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed. Syntax foreach (array as value) { code to be executed; } Example Try out following example to list out the values of an array. <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { echo “Value is $value n”; } ?> It will produce the following output − Value is 1 Value is 2 Value is 3 Value is 4 Value is 5 PHP while Loop The while statement will execute a block of code if and as long as a test expression is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false. Syntax while (condition) { code to be executed; } Example This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends. <?php $i = 0; $num = 50; while($i < 10) { $num–; $i++; } echo (“Loop stopped at i = $i and num = $num” ); ?> It will produce the following output − Loop stopped at i = 10 and num = 40 PHP do-while Loop The do-while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true. Syntax do { code to be executed; } while (condition); Example The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10 − <?php $i = 0; $num = 0; do { $i++; } while( $i < 10 ); echo (“Loop stopped at i = $i” ); ?> It will produce the following output − Loop stopped at i = 10 PHP break Statement The PHP break keyword is used to terminate the execution of a loop prematurely. The break statement is situated inside the statement block. It gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed. Example In the following example condition test becomes true when the counter value reaches 3 and loop terminates. <?php $i = 0; while( $i < 10) { $i++; if( $i == 3 )break; } echo (“Loop stopped at i = $i” ); ?> It will produce the following output − Loop stopped at i = 3 PHP continue Statement The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop. Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts. Example In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed. <?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { if( $value == 3 )continue; echo “Value is $value n”; } ?> It will produce the following output − Value is 1 Value is 2 Value is 4 Value is 5 Print Page Previous
Category: php
PHP – Functions
PHP – Functions ”; Previous Next Like most of the programming languages, a function in PHP is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse. PHP supports a structured programming approach by arranging the processing logic by defining blocks of independent reusable functions. The main advantage of this approach is that the code becomes easy to follow, develop and maintain. The following figure shows how the process of salary computation is successively broken down to independent and reusable functions. Types of Functions You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well. There are two types of functions in PHP − Built-in functions − PHP’s standard library contains a large number of built-in functions for string processing, file IO, mathematical computations and more. User-defined functions − You can create user-defined functions too, specific to the requirements of the programming logic. A function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment. There are two parts which should be clear to you − Creating a PHP Function Calling a PHP Function In fact you hardly need to create your own PHP function because there are already more than 1000 built-in library functions created for different area and you just need to call them according to your requirement. Please refer to PHP Function Reference for a complete set of useful functions. User-defined Functions in PHP Its very easy to create your own PHP function. Let”s start with a simple example after which we will elaborate how it works. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Example In this example, we create a function called writeMessage() and then call it to print a simple message − <?php /* Defining a PHP Function */ function writeMessage() { echo “You are really a nice person, Have a nice time!”; } /* Calling a PHP Function */ writeMessage(); ?> It will produce the following output − You are really a nice person, Have a nice time! Creating a Function in PHP Now let”s understand the process in detail. The first step is to write a function and then you can call it as many times as required. To create a new function, use the function keyword, followed by the name of the function you may want to use. In front of the name, put a parenthesis, which may or may not contain arguments. It is followed by a block of statements delimited by curly brackets. This function block contains the statements to be executed every time the function is called. The general syntax of defining a function is as follows − function foo($arg_1, $arg_2, $arg_n) { statements; return $retval; } If the function is intended to return some result back to the calling environment, there should be a return statement as the last statement in the function block. It is not mandatory to have a return statement, as even without it, the program flow goes back to the caller, albeit without carrying any value with it. Any valid PHP code may appear inside a function, even other functions and class definitions. Name of the function must follow the same rules as used to form the name of a variable. It should start with a letter or underscore, followed by any number of letters, numbers, or underscores. Here is a simple function in PHP. Whenever called, it is expected to display the message “Hello World”. function sayhello() { echo “Hello World”; } Calling a Function in PHP Once a function is defined, it can be called any number of times, from anywhere in the PHP code. Note that a function will not be called automatically. To call the function, use its name in a statement; the name of the function followed by a semicolon. <?php # define a function function sayhello(){ echo “Hello World”; } # calling the function sayhello(); ?> It will produce the following output − Hello World Assuming that the above script “hello.php” is present in the document root folder of the PHP server, open the browser and enter the URL as http://localhost/hello.php. You should see the “Hello World” message in the browser window. In this example, the function is defined without any arguments or any return value. In the subsequent chapters, we shall learn about how to define and pass arguments, and how to make a function return some value. Also, some advanced features of PHP functions such as recursive functions, calling a function by value vs by reference, etc. will also be explained in detail. Print Page Previous Next Advertisements ”;
PHP – Final Keyword
PHP – The “Final” Keyword ”; Previous Next The “final” keyword in PHP is used in the definition of a class, a method inside a class, as well as with the definition of a constant property of a class. A Class with “final” Keyword Let”s see how to create a class with the “final” keyword − final class myclass { /*class members*/ } The “final” keyword in class definition prevents such a class from being extended. In other words, you cannot use a final class as a parent. If you try, PHP parser throws an error <?php final class myclass { /* class body */ } class newclass extends myclass { /* class body */ } ?> When you run this code, it will show an error − PHP Fatal error: Class newclass may not inherit from final class (myclass) Method with “final” Keyword Here is how you can create a method with the “final” keyword − class myclass { final function myfunction() { /* function body */ } } Prefixing a method definition with the final keyword prevents it from being overridden in a child class. A class with final method can be extended, but the child class cannot override it. Example Take a look at the following example − <?php class myclass { final public function hello() { echo “Hello World!”; } } class newclass extends myclass { public function hello() { echo “Hello PHP!”; } } ?> When you run this code, it will show an error − PHP Fatal error: Cannot override final method myclass::hello() in hello.php Constant with “final” Keyword You can also declare a constant in a class with the final keyword, starting from PHP 8.1.0 onwards. final public const NAME = “My Class”; If you try to override a final constant from parent class in a child class, an error is encountered. <?php class myclass { final public const NAME = “My Class”; final public function hello() { echo “Hello World!”; } } class newclass extends myclass { public const NAME = “New Class”; } ?> When you run this code, it will show an error − Fatal error: newclass::NAME cannot override final constant myclass::NAME Example The following PHP script contains a parent class ellipse with a PI constant and area() method both declared as final. They are inherited by the circle class. The area() function calculates the area of circle. <?php class ellipse { final public const PI=22/7; private float $a, $b; public function __construct($x, $y) { $this->a = $x; $this->b = $y; } final public function area() : float { return self::PI*$this->a*$this->b; } } class circle extends ellipse { public function __construct(float $x) { parent::__construct($x, $x); } } $c1 = new circle(5); echo “Area: ” . $c1->area() . PHP_EOL; ?> It will produce the following output − Area: 78.571428571429 Note that the instance variables or properties of a class cannot be declared as final. Print Page Previous Next Advertisements ”;
PHP – Anonymous Classes
PHP – Anonymous Classes ”; Previous Next The release of version 7.0 is an important milestone in the evolution of PHP language, when a lot of new features were introduced. The feature of Anonymous class was also made available in PHP version 7.0. As the term “anonymous” suggests, it is a class without a (programmer declared) name. The usual practice is to define a class with a certain identifier, so that it can be used repeatedly. The anonymous class, on the other hand is for one-time use only. $obj = new class() { /* class body */ }; Apart from this class not having a name, it is similar to a normal named class, in the sense it can contain properties and methods. Its functionality is no different from that of an object of a named class. An anonymous class might be used over a named class especially when the class does not need to be documented, and when the class is used only once during execution. Anonymous classes are useful when simple, one-off objects need to be created. Example In the following code, an anonymous class is instantiated and stored in $obj object. The class includes definitions of addition() and division() methods, which are called with the $obj object. <?php $obj = new class(10) { private int $x; function __construct($x) { $this->x = $x; } public function addition($x) { return $this->x+$x; } public function division($x) { return $this->x/$x; } }; echo “Addition: ” . $obj->addition(20) . PHP_EOL; echo “Division: ” . $obj->division(20) . PHP_EOL; ?> It will produce the following output − Addition: 30 Division: 0.5 Anonymous Class as a Child Class An anonymous class can do everything that a normal class can. It can extends another class, implement an interface or even use a trait. Example In the example below, the anonymous class is a child class, extending a parent already available. <?php class myclass { public function hello() { echo “Hello World!” . PHP_EOL; } } $obj = new class(“Neena”) extends myclass { private string $nm; function __construct($x) { $this->nm = $x; } public function greeting() { parent::hello(); echo “Welcome ” . $this->nm . PHP_EOL; } }; $obj->greeting(); ?> It will produce the following output − Hello World! Welcome Neena Example Although the anonymous class doesn’t have any user defined name, PHP does assign it an internal name, which can be obtained with the built-in get_class() function as follows − <?php $obj = new class() { function greeting() { echo “Hello World” . PHP_EOL; } }; $obj->greeting(); echo “Name of class: ” . get_class($obj); ?> It will produce the following output − Hello World Name of class: class@anonymousC:xampphtdocshello.php:2$0 PHP parser assigns the internal name randomly. Print Page Previous Next Advertisements ”;
PHP – Encapsulation
PHP – Encapsulation ”; Previous Next PHP implements encapsulation, one of the important principles of OOP with access control keywords: public, private and protected. Encapsulation refers to the mechanism of keeping the data members or properties of an object away from the reach of the environment outside the class, allowing controlled access only through the methods or functions available in the class. The following diagram illustrates the principle of encapsulation in object-oriented programming methodology. PHP’s keywords list contains the following keywords that determine the accessibility of properties and methods of an object, which is an instance of a class in PHP − Public − Class members are accessible from anywhere, even from outside the scope of the class, but only with the object reference. Private − Class members can be accessed within the class itself. It prevents members from outside class access even with the reference of the class instance. Protected − Members can be accessed within the class and its child class only, nowhere else. These three keywords “public, private and protected” are often called access modifiers. They are also referred as visibility modes, as they decide upto what extent a certain class member is available. Public Members In PHP, the class members (both member variables as well as member functions) are public by default. Example In the following program, the member variables title and price of the object are freely accessible outside the class because they are public by default, if not otherwise specified. <?php class Person { /* Member variables */ var $name; var $age; /*Constructor*/ function __construct(string $param1=”Ravi”, int $param2=28) { $this->name = $param1; $this->age = $param2; } function getName() { echo “Name: $this->name” . PHP_EOL;; } function getAge() { echo “Age: $this->age” . PHP_EOL;; } } $b1 = new Person(); $b1->getName(); $b1->getAge(); echo “Name : $b1->name Age: $b1->age” . PHP_EOL; ?> It will produce the following output − Name: Ravi Age: 28 Name : Ravi Age: 28 Note that the properties all the class members are public by default, you can explicitly declare them as public if desired. As a result, the instance methods getName() and getAge() can be called from outside the class. Since properties name and age are also public, hence they can also be accessed outside the class, something which is not desired as per the principle of encapsulation. Private Members As mentioned above, the principle of encapsulation requires that the member variables should not be accessible directly. Only the methods should have the access to the data members. Hence, we need to make the member variables private and methods public. Example Let us change the declaration of name and age properties to private and run the following PHP script − <?php class Person { /* Member variables */ private $name; private $age; /*Constructor*/ function __construct(string $param1=”Ravi”, int $param2=28) { $this->name = $param1; $this->age = $param2; } public function getName() { echo “Name: $this->name” . PHP_EOL;; } public function getAge(){ echo “Age: $this->age” . PHP_EOL;; } } $b1 = new Person(); $b1->getName(); $b1->getAge(); echo “Name : $b1->name Age: $b1->age” . PHP_EOL; ?> It will produce the following output − Name: Ravi Age: 28 PHP Fatal error: Uncaught Error: Cannot access private property Person::$name in person.php:27 The error message tells the reason that a private property cannot be accessed from a public scope. Protected Members The effect of specifying protected access to a class member is effective in case of class inheritance. We know that public members are accessible from anywhere outside the class, and private members are denied access from anywhere outside the class. The protected keyword grants access to an object of the same class and an object of its inherited class, denying it to any other environment. Example Let us inherit the person class and define a student class. We shall change the name property from private to protected. The student class has a new public method getDetails() that prints the values of name and age properties. Person class <?php class Person { /* Member variables */ protected $name; private $age; /*Constructor*/ function __construct(string $param1=”Ravi”, int $param2=28) { $this->name = $param1; $this->age = $param2; } public function getName(){ echo “Name: $this->name” . PHP_EOL;; } public function getAge() { echo “Age: $this->age” . PHP_EOL;; } } Student class class student extends Person { public function getDetails() { echo “My Name: $this->name” . PHP_EOL; echo “My age: $this->age” . PHP_EOL; } } $s1 = new student(); $s1->getDetails(); ?> It will produce the following output − My Name: Ravi PHP Warning: Undefined property: student::$age in person.php on line 28 My age: The following table illustrates the rules of accessibility of class members in PHP − Print Page Previous Next Advertisements ”;
PHP – Static Methods
PHP â Static Methods ”; Previous Next The “static” keyword in PHP is used to define static properties and static methods in a PHP class. It may be noted that the static keyword is also used to define static variable, and static anonymous functions. This chapter discusses static methods in a PHP class. In a class definition, a function declared with a static qualifier becomes its static method. class myclass { public static function myStaticMethod() { // … } You donât need to create the instance of the class to call its static method. The static method is called by the class name though the scope resolution operator. The syntax of a static method call is − myclass::myStaticMethod(); As the static methods are callable without creating an instance of the class, the pseudo-variable $this is not available inside static methods. A static method is allowed to be called by an object, although calling an instance method as a static method raises error. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } public function myinstancemethod() { echo “This is an instance method”. PHP_EOL; } } myclass::mystaticmethod(); $obj = new myclass; $obj->myinstancemethod(); $obj->mystaticmethod(); myclass::myinstancemethod(); ?> It will produce the following output − This is a static method This is an instance method This is a static method PHP Fatal error: Uncaught Error: Non-static method myclass::myinstancemethod() cannot be called statically The “self” Keyword in Static Method If you need to call a static method from inside an instance method defined in the same class, you have to use self keyword referring to the name of the class, followed by the scope resolution operator (such as self::mystaticmethod) <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } public function myinstancemethod() { echo “This is an instance method”. PHP_EOL; echo “calling static method from instance method” . PHP_EOL; self::mystaticmethod(); } } $obj = new myclass; $obj->myinstancemethod(); ?> It will produce the following output − This is an instance method calling static method from instance method This is a static method Using the “parent” Keyword In case of inheritance, a static method defined in a base class may be called by an object of derived class, or from inside an instance method of the derived class, by referring it with the “parent” keyword. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } public function myinstancemethod() { echo “This is an instance method”. PHP_EOL; echo “calling static method from instance method” . PHP_EOL; self::mystaticmethod(); } } class mynewclass extends myclass { public function myfunction() { echo “This an instance method of the derived class” . PHP_EOL; echo “Calling static method of the parent class” . PHP_EOL; parent::mystaticmethod(); } } $obj = new mynewclass; mynewclass::mystaticmethod(); $obj->myfunction(); ?> It will produce the following output − This is a static method This an instance method of the derived class Calling static method of the parent class This is a static method Static Method Inside Another Class It is entirely possible to call the static method from one class in another. You have to qualify its name with its class name followed by the scope resolution operator. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } } #this is not a derived class class mynewclass { public function myfunction() { echo “This an instance method” . PHP_EOL; echo “Calling static method of the another class” . PHP_EOL; myclass::mystaticmethod(); } } $obj = new mynewclass; $obj->myfunction(); ?> It will produce the following output − This an instance method Calling static method of another class This is a static method Since $this pseudo-variable is not available for a static method, the instance variables of an object cannot be accessed inside a static method. It can process only the static properties of the class. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; function __construct() { self::$var1++; echo “object number “. self::$var1 . PHP_EOL; } public static function mystaticmethod() { echo “Number of objects available: ” . self::$var1 . PHP_EOL; } } for ($i=1; $i<=3; $i++) { $obj = new myclass; } myclass::mystaticmethod(); ?> It will produce the following output − object number 1 object number 2 object number 3 Number of objects available: 3 Print Page Previous Next Advertisements ”;
Object Oriented Programming in PHP ”; Previous Next We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects. Object Oriented Concepts Before we go in detail, lets define important terms related to Object Oriented Programming. Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object. Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance. Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created. Member function − These are the function defined inside a class and are used to access object data. Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class. Parent class − A class that is inherited from by another class. This is also called a base class or super class. Child Class − A class that inherits from another class. This is also called a subclass or derived class. Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task. Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation. Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted). Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object. Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class. Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope. Defining PHP Classes The general form for defining a new class in PHP is as follows − <?php class phpClass { var $var1; var $var2 = “constant string”; function myfunc ($arg1, $arg2) { [..] } [..] } ?> Here is the description of each line − The special form class, followed by the name of the class that you want to define. A set of braces enclosing any number of variable declarations and function definitions. Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value. Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data. Example Here is an example which defines a class of Books type − <?php class Books { /* Member variables */ var $price; var $title; /* Member functions */ function setPrice($par){ $this->price = $par; } function getPrice(){ echo $this->price .”<br/>”; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title .” <br/>”; } } ?> The variable $this is a special variable and it refers to the same object ie. itself. Creating Objects in PHP Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator. $physics = new Books; $maths = new Books; $chemistry = new Books; Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables. Calling Member Functions After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set title and prices for the three books by calling member functions. $physics->setTitle( “Physics for High School” ); $chemistry->setTitle( “Advanced Chemistry” ); $maths->setTitle( “Algebra” ); $physics->setPrice( 10 ); $chemistry->setPrice( 15 ); $maths->setPrice( 7 ); Now you call another member functions to get the values set by in above example − $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice(); This will produce the following result − Physics for High School Advanced Chemistry Algebra 10 15 7 Constructor Functions Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions. PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function. Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation. function __construct( $par1, $par2 ) { $this->title = $par1; $this->price = $par2; } Now we don”t need to call set function separately to set price
PHP – Recursive Functions
PHP – Recursive Functions ”; Previous Next A recursive function is such a function that calls itself until a certain condition is satisfied. In PHP, it is possible to defines a recursive function. Recursion is used when a certain problem is defined in terms of itself. Sometimes, it can be tedious to solve a problem using iterative approach. Recursive approach provides a very concise solution to seemingly complex problems. Recursion in PHP is very similar to the one in C and C++. Recursive functions are particularly used in traversing nested data structures, and searching or sorting algorithms. Binary tree traversal, heap sort and finding shortest route are some of the cases where recursion is used. Calculation of Factorial using Recursion The most popular example of recursion is calculation of factorial. Mathematically factorial is defined as − n! = n × (n-1)! It can be seen that we use factorial itself to define factorial. Hence, this is a fit case to write a recursive function. Let us expand the above definition for calculation of factorial value of 5 5! = 5 × 4! 5 × 4 × 3! 5 × 4 × 3 × 2! 5 × 4 × 3 × 2 × 1! 5 × 4 × 3 × 2 × 1 = 120 While we can perform this calculation using a loop, its recursive function involves successively calling it by decrementing the number till it reaches 1. Example Following is the recursive function to calculate factorial. <?php function factorial ($n) { if ($n == 1) { echo $n . PHP_EOL; return 1; } else { echo “$n * “; return $n*factorial($n-1); } } echo “Factorial of 5 = ” . factorial(5); ?> It will produce the following output − 5 * 4 * 3 * 2 * 1 Factorial of 5 = 120 Binary Search using Recursion Let us have a look at another example to understand how recursion works. The problem at hand is to check whether a given number is present in a list. While we can perform a sequential search for a certain number in the list using a for loop and comparing each number, the sequential search is not efficient especially if the list is too large. Here, we can use the binary search algorithm that checks if the index ”high” is greater than index ”low. Based on the value present at ”mid” variable, the function is called again to search for the element. We have a list of numbers, arranged in ascending order. Then, we find the midpoint of the list and restrict the checking to either left or right of midpoint depending on whether the desired number is less than or greater than the number at midpoint. The following diagram shows how binary search works − Example The following code implements the recursive binary searching technique − <?php function bsearch($my_list, $low, $high, $elem) { if ($high >= $low) { $mid = intval(($high + $low)/2); if ($my_list[$mid] == $elem) return $mid; elseif ($my_list[$mid] > $elem) return bsearch($my_list, $low, $mid – 1, $elem); else return bsearch($my_list, $mid + 1, $high, $elem); } else return -1; } $list = [5,12,23, 45, 49, 67, 71, 77, 82]; $num = 67; $result = bsearch($list,0,count($list)-1, $num); if ($result != -1) echo ” Number $num found at index ” . $result; else echo “Element not found!”; ?> It will produce the following output − Number 67 found at index 5 You can check the output for different numbers present in the given list, as well as those which are not present in the list. Print Page Previous Next Advertisements ”;
PHP â Constructor and Destructor ”; Previous Next As in most of the object-oriented languages, you can define a constructor function in a class in PHP also. When you declare an object with the new operator, its member variables are not assigned any value. The constructor function is used to initialize every new object at the time of declaration. PHP also supports having a destructor function that destroys the object from the memory as it no longer has any reference. The __construct() Function PHP provides a __construct() function that initializes an object. __construct(mixed …$values = “”): void The constructor method inside a class is called automatically on each newly created object. Note that defining a constructor is not mandatory. However, if present, it is suitable for any initialization that the object may need before it is used. You can pass as many as arguments you like into the constructor function. The __construct() function doesnât have any return value. Let us define a constructor in the Book class used in the previous chapter <?php class Book { /* Member variables */ var $price; var $title; /*Constructor*/ function __construct(){ $this->title = “PHP Fundamentals”; $this->price = 275; } /* Member functions */ function getPrice() { echo “Price: $this->price n”; } function getTitle(){ echo “Title: $this->title n”; } } $b1 = new Book; $b1->getTitle(); $b1->getPrice(); ?> It will produce the following output − Title: PHP Fundamentals Price: 275 Parameterized Constructor The member variables of $b1 have been initialized without having to call setTitle() and setPrice() methods, because the constructor was called as soon as the object was declared. However, this constructor will be called for each object, and hence each object has the same values of title and price properties. To initialize each object with different values, define the __construct() function with parameters. Change the definition of __construct() function to the following − function __construct($param1, $param2) { $this->title = $param1; $this->price = $param2; } To initialize the object, pass values to the parameters inside a parenthesis in the declaration. $b1 = new Book(“PHP Fundamentals”, 375); Example Now, you can have each object with different values to the member variables. <?php class Book { /* Member variables */ var $price; var $title; /*Constructor*/ function __construct($param1, $param2) { $this->title = $param1; $this->price = $param2; } /* Member functions */ function getPrice(){ echo “Price: $this->price n”; } function getTitle(){ echo “Title: $this->title n”; } } $b1 = new Book(“PHP Fundamentals”, 375); $b2 = new Book(“PHP Programming”, 450); $b1->getTitle(); $b1->getPrice(); $b2->getTitle(); $b2->getPrice(); ?> It will produce the following output − Title: PHP Fundamentals Price: 375 Title: PHP Programming Price: 450 Constructor Overloading Method overloading is an important concept in object-oriented programming, where a class may have more than one definitions of constructor, each having different number of arguments. However, PHP doesnât support method overloading. This limitation may be overcome by using arguments with default values in the constructor function. Change the __construct() function to the following − function __construct($param1=”PHP Basics”, $param2=380) { $this->title = $param1; $this->price = $param2; } Now, declare an object without passing parameters, and the other with parameters. One without parameters will be initialized with default arguments, the other with the values passed. $b1 = new Book(); $b2 = new Book(“PHP Programming”, 450); It will produce the following output − Title: PHP Basics Price: 380 Title: PHP Programming Price: 450 Type Declaration in Constructor Since PHP (version 7.0 onwards) allows scalar type declarations for function arguments, the __construct() function may be defined as − function __construct(string $param1=”PHP Basics”, int $param2=380) { $this->title = $param1; $this->price = $param2; } In the earlier versions of PHP, using the name of class to define a constructor function was allowed, but this feature has been deprecated since PHP version 8.0. The __destruct() Function PHP also has a __destructor() function. It implements a destructor concept similar to that of other object-oriented languages, as in C++. The destructor method will be called as soon as there are no other references to a particular object. __destruct(): void The __destruct() function doesnât have any parameters, neither does it have any return value. The fact that the __destruct() function is automatically called when any object goes out of scope, can be verified by putting var_dump($this) inside the function. As mentioned above, $this carries the reference to the calling object, the dump shows that the member variables are set to NULL Add destructor function in the Book class as follows − function __destruct() { var_dump($this); echo “object destroyed”; } As the program exits, the following output will be displayed − object(Book)#1 (2) { [“price”]=> NULL [“title”]=> NULL } object destroyed Print Page Previous Next Advertisements ”;
PHP – Traits
PHP â Traits ”; Previous Next In PHP, a class can inherit only from one parent class, multiple inheritance is not defined in PHP. Traits in PHP have been introduced to overcome this limitation. You can define one or more method in a trait, which can be reused freely in various independent classes. Syntax The “trait” keyword is used as per the following syntax − trait mytrait { function method1() { /*function body*/ } function method2() { /*function body*/ } } To be able to call the methods in a trait, it needs to made available to another class with use keyword. Example 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. <?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 Example A trait can be used in more than one classes. The following example has a mytrait with avg() function int it. It is used inside a marks class. The percent() method internally calls the avg() function from the trait. Take a look at the following example − <?php trait mytrait { function avg($x, $y) { return ($x+$y)/2; } } class marks { use mytrait; private int $m1, $m2; function __construct($x, $y) { $this->m1 = $x; $this->m2 = $y; } function percent():float { return $this->avg($this->m1, $this->m2); } } $obj = new marks(50, 60); echo “percentage: ” . $obj->percent(); ?> It will produce the following output − percentage: 55 Using Multiple Traits A class can use more than one traits. Here we have two traits with one function each performing addition and multiplication of two numbers. Both are used inside a third class. <?php trait addition { function add($x, $y) { return $x+$y; } } trait multiplication { function multiply($x, $y) { return $x*$y; } } class numbers { use addition, multiplication; private int $m1, $m2; function __construct($x, $y) { $this->m1 = $x; $this->m2 = $y; } function calculate():array { $arr = [$this->add($this->m1, $this->m2), $this->multiply($this->m1, $this->m2)]; return $arr; } } $obj = new numbers(50, 60); $res = $obj->calculate(); echo “Addition: ” . $res[0] . PHP_EOL; echo “Multiplication: ” . $res[1] . PHP_EOL; ?> It will produce the following output − Addition: 110 Multiplication: 3000 Overriding Trait Function When a class uses a certain trait, its function are available to it just as a child class inherits the parent methods. The trait function may also be overridden. <?php trait mytrait { public function sayHello() { echo ”Hello World!”; } } class myclass { use mytrait; public function sayHello() { echo ”Hello PHP!”; } } $o = new myclass(); $o->sayHello(); ?> It will produce the following output − Hello PHP! The “insteadof” Keyword Sometimes, more two traits might have same name of the function. Hence, using them in a class creates ambiguous situation. PHP provides insteadof keyword to tell the parser function from which trait you intend to use. <?php trait mytrait { public function sayHello() { echo ”Hello World!”; } } trait newtrait { public function sayHello() { echo ”Hello PHP!”; } } class myclass { use mytrait, newtrait{ newtrait::sayHello insteadof mytrait; } } $o = new myclass(); $o->sayHello(); ?> It will produce the following output − Hello PHP! Aliasing a Trait Function If you want to be able to call functions from both traits even if they have function with same name, a workaround is to specify an alias name to one of them. Example In the following example, we will call sayHello() from mytrait as hello() − <?php trait mytrait { public function sayHello() { echo ”Hello World!” . PHP_EOL; } } trait newtrait { public function sayHello() { echo ”Hello PHP!” . PHP_EOL; } } class myclass { use mytrait, newtrait{ mytrait::sayHello as hello; newtrait::sayHello insteadof mytrait; } } $o = new myclass(); $o->hello(); $o->sayHello(); ?> It will produce the following output − Hello World! Hello PHP! Print Page Previous Next Advertisements ”;