0% found this document useful (0 votes)
1 views

PHP Unit 3_4

The document covers PHP functions, strings, and object-oriented programming concepts, focusing on user-defined functions, recursion, and built-in functions. It explains function parameters, variable scope, and provides examples of string manipulation functions. Additionally, it discusses date and time functions in PHP, highlighting how to obtain and format date and time values.

Uploaded by

anithapriyanka3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

PHP Unit 3_4

The document covers PHP functions, strings, and object-oriented programming concepts, focusing on user-defined functions, recursion, and built-in functions. It explains function parameters, variable scope, and provides examples of string manipulation functions. Additionally, it discusses date and time functions in PHP, highlighting how to obtain and format date and time values.

Uploaded by

anithapriyanka3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PHP : UNIT-3 & 4

 Functions
 Strings
 Class & Objects
Functions in PHP, Function definition, Creating and invoking user-defined functions, Formal parameters
versus actual parameters, Function and variable scope, Recursion, Library functions, Date and Time
Functions
Strings in PHP: What is String? Creating and Declaring String, String Functions

Functions in PHP

 PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP.
 In PHP, we can define Conditional function, Function within Function and Recursive function
also.
 Built-in functions, also called predefined or library functions, are included in PHP by default.
 They perform common tasks like handling strings, arrays, files, math operations, and databases.
 These functions save time and effort as they are already implemented and available for use.
 PHP offers a vast range of built-in functions, providing developers with tools to complete tasks
quickly and efficiently.
 Example:
$string = "Hello, world!";
$length = strlen($string);
// Built-in function to find the length of a string

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of
function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow
of the application because every logic is divided in the form of functions.

User Defined Functions

 User-defined functions are created by the programmer to perform specific tasks according to their
requirements.
 These functions are declared using the function keyword followed by a function name and a block
of code encapsulated within curly braces {}.
 They can accept parameters (input data) and return values (output data) using the return statement.
 User-defined functions provide a way to encapsulate reusable code, promote modularity, and
enhance code readability and maintainability.
 Any valid PHP code may appear inside a function, even other functions and class definitions.
 Functions need not be defined before they are referenced, except when a function is conditionally
defined.
 When a function is defined in a conditional manner, its definition must be processed prior to being
called.
 All functions and classes in PHP have the global scope - they can be called outside a function
even if they were defined inside and vice versa.
 A function may be defined using syntax such as the following:
function functionname()
{
//code to be executed
}
Example:
function greet($name) {
return "Hello, $name!";
}
Function arguments
 Information may be passed to functions via the argument list, which is a comma-delimited list of
expressions. The arguments are evaluated from left to right, before the function is actually called
(eager evaluation).
 PHP supports passing arguments by value (the default), passing by reference, and default
argument values. Variable-length argument lists and Named Arguments are also supported.
 The list of function arguments may include a trailing comma, which will be ignored. That is
particularly useful in cases where the list of arguments is long or contains long variable names,
making it convenient to list arguments vertically.
 By default, function arguments are passed by value (so that if the value of the argument within the
function is changed, it does not get changed outside of the function). To allow a function to
modify its arguments, they must be passed by reference.
 To have an argument to a function always passed by reference, prepend an ampersand (&) to the
argument name in the function definition:
 A function may define default values for arguments using syntax similar to assigning a variable.
The default is used only when the parameter is not specified; in particular, note that passing null
does not assign the default value.
 The default value must be a constant expression, not (for example) a variable, a class member or a
function call.
 Note that any optional arguments should be specified after any required arguments, otherwise they
cannot be omitted from calls.
 PHP has support for variable-length argument lists in user-defined functions by using the ... token.
 Argument lists may include the ... token to denote that the function accepts a variable number of
arguments. The arguments will be passed into the given variable as an array.

PHP Function Parameters

Function parameters are placeholders or variables declared within the parentheses of a function. They
define the input required by the function when it’s called and pass values or variables into the function for
processing.

How to Call Functions in PHP

To call a function, first make sure the function is defined in your PHP code. Functions are defined before
they are called, either in the same file or in an included file.
Then, add the function name followed by parentheses that may contain any required arguments.

Function and variable scope

In PHP, function and variable scope determine where variables can be accessed and modified within the
code.

1. Local Scope:
 Variables declared inside a function are local to that function. They are only accessible within the
function's code block.
 Any changes made to a local variable within a function do not affect variables with the same name
outside the function.
2. Global Scope:
 Variables declared outside of any function are considered global. They are accessible from
anywhere within the script, including inside functions.
 However, using global variables extensively can make your code harder to understand and
maintain. It's generally recommended to use local variables and function arguments whenever
possible.
3. Static Scope (Within Functions):
 Static variables declared within a function retain their value between function calls, unlike local
variables which are recreated each time the function is called.
 This allows you to maintain state within a function across multiple calls.

Recursion
It is possible to call recursive functions in PHP.
In PHP, recursion refers to a programming technique where a function calls itself directly or indirectly.
This creates a loop-like behavior, but with some key differences.

Concept of Recursion:

A recursive function has a base case, which is a condition that stops the recursive calls and returns a final
result.
The recursive case involves the function calling itself with modified arguments that bring it closer to the
base case. This creates a series of nested function calls.

Example (Factorial Calculation):

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For
example, factorial of 5 (written as 5!) is 5 * 4 * 3 * 2 * 1 = 120.

function factorial($n) {
if ($n === 0) { // Base case: factorial of 0 is 1
return 1;
} else {
// Recursive case: call factorial with n-1, multiply by n
return $n * factorial($n - 1);
}
}

$number = 5;
$result = factorial($number);

echo "Factorial of $number: $result";

Explanation:

factorial(5) is called.
Since 5 is not equal to 0 (not the base case), it enters the recursive case.
The function calls itself with factorial(4).
Following the same logic, factorial(4) calls factorial(3).
This continues until factorial(0) is called.
At factorial(0), the base case is met, returning 1.
factorial(1) now receives 1 (from factorial(0)) and returns 1 (since 1! is 1).
factorial(2) receives 1 (from factorial(1)) and returns 2 (1 * 2).
This process continues up the chain of recursive calls.
Finally, factorial(5) receives the result from factorial(4) (which is the accumulated product from previous
calls) and returns 5 * 120 (120 being the result of factorial(4)).

Date & Time Functions


In PHP programming, you often need to manage or manipulate date and time values.
Getting Date & Time in PHP
There are two ways to obtain the date and time in PHP. You can use the date() function or the DateTime
class.
Using the date() Function
The date() function obtains the current date and time as a formatted string. It also allows you to specify
the format of the output.

Formatting options in date() function:

d: Represents day of the month; two digits with leading zeros (01 or 31).
D: Represents day of the week in the text as an abbreviation (Mon to Sun).
m: Represents month in numbers with leading zeros (01 or 12).
M: Represents month in text, abbreviated (Jan to Dec).
y: Represents year in two digits (24).
Y: Represents year in four digits (2024).

The time() function is used to get the current time as a Unix timestamp (the number of seconds since the
beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
h: Represents hour in 12-hour format with leading zeros (01 to 12).
H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).

mktime — Get Unix timestamp for a date


Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer
containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time
specified.
The other functions that are frequently used are :
checkdate - Validate a Gregorian date
date_format - Returns date formatted according to given format.
date - Returns a formatted date string.
getdate - Get date/time information
gettimeofday - Get current time
localtime - Get the local time
mktime - Get Unix timestamp for a date
time - Return current Unix timestamp, Returns the current timestamp.

Strings in PHP: Creating and Declaring String


 A string is a series of characters, where a character is the same as a byte.
 A string literal can be either single quoted or double quoted;
 The simplest way to specify a string is to enclose it in single quotes (the character '). To specify a
literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All
other instances of backslash will be treated as a literal backslash.
 Double quoted strings perform action on special characters whereas single quoted strings does not
perform such actions, it returns the string like it was written, with the variable name.
 For example:
o $x = “name”;
o echo “Hello $x”; //displays Hello name
o echo ‘Hello $x’; // displays Hello $x
String Functions

Function Usage Syntax Return Value Example Output


chr Generate a chr(int $codepoint): A single-character echo chr(52) 4
single-byte string string containing the
string from a specified byte.
number
echo Output one echo(string No value is returned. echo "hello"; hello
or more ...$expressions)
strings
explode Split a string explode(string Returns an array of $pizza = "piece1 piece2 piece3 piece1
by a string $separator, string strings created by piece4 piece5 piece6";
$string, int $limit = splitting the string $pieces = explode(" ", $pizza);
PHP_INT_MAX): parameter on echo $pieces[0];
array boundaries formed by
the separator.
implode Join array implode(string Returns a string $array = ['lastname', 'email', string(20) "lastname,email,phone"
elements with $separator, array containing a string 'phone'];
a string $array): string representation of all the var_dump(implode(",", $array));
array elements in the
same order, with the
separator string
between each element.
ltrim Strip ltrim(string $string, Returns a string with $str = "\n\n\nHello World!"; Without ltrim: Hello World!
whitespace string $characters = whitespace stripped echo "Without ltrim: " . $str; With ltrim: Hello World!
(or other " \n\r\t\v\x00"): from the beginning of echo "<br>";
characters) string string. echo "With ltrim: " . ltrim($str);
from the
beginning of
a string
md5 Calculate the md5(string $string, Returns the hash as a $str = "Hello"; 8b1a9953c4611296a827abf8c47804d7
md5 hash of bool $binary = 32-character echo md5($str);
a string false): string hexadecimal number.
print Output a print(string Returns 1, always. $str = "Hello world!"; Hello world!
string $expression): int print $str;
rtrim Strip rtrim(string $string, Returns the modified $str = "Hello World!"; Hello World!
Function Usage Syntax Return Value Example Output
whitespace string $characters = string. echo $str . "<br>"; Hello
(or other " \n\r\t\v\x00"): echo rtrim($str,"World!");
characters) string
from the end
of a string
str_contains Determine if str_contains(string Returns true if needle is $string = 'The lazy fox jumped The string 'lazy' was found in the
a string $haystack, string in haystack, false over the fence'; string
contains a $needle): bool otherwise.
given if (str_contains($string, 'lazy')) {
substring echo "The string 'lazy' was
found in the string\n";
str_repeat Repeat a str_repeat(string Returns the repeated echo str_repeat("-=", 10); -=-=-=-=-=-=-=-=-=-=
string $string, int $times): string.
string
str_replace Replace all str_replace( Returns a string or an echo Hello PHP!
occurrences array|string array with the replaced str_replace("world","PHP","Hello
of the search $search, values. world!");
string with array|string
the $replace,
replacement string|array
string $subject,
int &$count =
null
): string|array
str_split Convert a str_split(string If the optional length $str = "Hello Friend"; Array
string to an $string, int $length parameter is specified, $arr1 = str_split($str, 3); (
array = 1): array the returned array will [0] => Hel
be broken down into [1] => lo
chunks with each being [2] => Fri
length in length, except [3] => end
the final chunk which )
may be shorter if the
string does not divide
evenly. The default
length is 1, meaning
Function Usage Syntax Return Value Example Output
every chunk will be one
byte in size.
strcmp Binary safe strcmp(string Returns -1 if string1 is echo strcmp("Hello 0
string $string1, string less than string2; 1 if world!","Hello world!");
comparison $string2): int string1 is greater than
string2, and 0 if they
are equal.
strlen Get string strlen(string Returns The length of $str = 'abcdef'; 6
length $string): int the string in bytes. echo strlen($str);
strpos Find the strpos(string Returns the position of echo strpos("I love php, I love 7
position of $haystack, string where the needle exists php too!","php");
the first $needle, int $offset relative to the
occurrence of = 0): int|false beginning of the
a substring in haystack string
a string (independent of offset).
Also note that string
positions start at 0, and
not 1.
strrev Reverse a strrev(string Returns the reversed echo strrev("Hello world!"); !dlrow olleH
string $string): string string.
strtolower Make a strtolower(string Returns the lowercased $str = "Mary Had A Little Lamb mary had a little lamb and she loved it
string $string): string string. and She LOVED It So"; so
lowercase $str = strtolower($str);
echo $str;
strtoupper Make a strtoupper(string Returns the uppercased $str = "Mary Had A Little Lamb MARY HAD A LITTLE LAMB
string $string): string string. and She LOVED It So"; AND SHE LOVED IT SO
uppercase $str = strtoupper($str);
echo $str;
substr Return part substr(string Returns the portion of $rest = substr("abcdef", 0, -1); abcde
of a string $string, int $offset, string specified by the
?int $length = null): offset and length
string parameters.
trim Strip trim(string $string, Returns The trimmed $str = "Hello World!"; Hello World!
whitespace string $characters = string. echo $str . "<br>"; llo Worl
(or other " \n\r\t\v\x00"): echo trim($str,"Hed!");
Function Usage Syntax Return Value Example Output
characters) string
from the
beginning
and end of a
string
wordwrap Wraps a wordwrap( Wraps a string to a $text = "The quick brown fox The quick brown fox
string to a string $string, given number of jumped over the lazy dog."; jumped over the lazy
given number int $width = 75, characters using a $newtext = wordwrap($text, 20, dog.
of characters string $break = string break character. "<br />\n");
"\n", Returns the given string echo $newtext;
bool wrapped at the
$cut_long_words = specified length.
false
): string

o For the remaining functions and additional information, please refer to::
o https://www.php.net/manual/en/ref.strings.php
Class &Objects in PHP: What is Class & Object, Creating and accessing a Class &Object, Object
properties, object methods, Overloading, inheritance, Constructor and Destructor

PHP includes a complete object model. Some of its features are: visibility, abstract and final classes and
methods, additional magic methods, interfaces, and cloning.
PHP treats objects in the same way as references or handles, meaning that each variable contains an
object reference rather than a copy of the entire object.

CLASSES & OBJECTS


A class is a fundamental concept in PHP programming that serves as a blueprint or template that outlines
the structure and behaviour of objects.
A class act as a foundation for creating objects of a specific type by providing a set of predefined
properties and methods.
A class is defined with the keyword class, followed by a class name, and a pair of curly braces which
enclose the definitions of the properties and methods belonging to the class.

Declaring a Class
A class definition includes the class name and the properties and methods of the class. Here’s the syntax
for a class definition:
Syntax:

class classname{

// properties;
//methods
}
A class may contain its own constants, variables called "properties", and functions called "methods".

Defining Properties
Class member variables are called properties. They are defined by using at least one modifier (such as
Visibility, Static Keyword) followed by a type declaration, followed by a normal variable declaration.
Class properties may be defined as public, private, or protected. Properties declared without any explicit
visibility keyword are defined as public.

Example:
public $var1 = 'hello ';

Declaring Methods
A method is a function defined inside a class. Although PHP imposes no special restrictions, most
methods act only on data within the object in which the method resides. Within a method, the $this
variable contains a reference to the object on which the method was called. Methods use the $this
variable to access the properties of the current object and to call other methods on that object.
To create a new object from a class, use the new statement to instantiate a class.

Accessing Object Properties and Methods


After creating an object, its properties and methods can be accessed using the object operator (->).
The visibility of a property, a method or a constant can be defined by prefixing the declaration with the
keywords public, protected or private. Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inheriting and parent
classes. Members declared as private may only be accessed by the class that defines the member.
Class methods may be defined as public, private, or protected. Methods declared without any explicit
visibility keyword are defined as public.

Example:
<?php
class SimpleClass
{
// property declaration
public $var = ‘value';

// method declaration
public function displayVar() {
echo $this->var;
}
}
$newClass1 = new SimpleClass; //creating a new object for the class
$newClass1->displayVar();
?>

Lets demonstrate the concept of classes and objects with an example:

Consider a class Book to hold information about its title and author. The class Book is defined as:

class Book {
// Define properties (variables) to hold book information
public $title;
public $author;

// Define a method (function) to greet the reader


public function greetReader() {
echo "Welcome! Pick up a copy of " . $this->title . " by " . $this->author . ".";
}
}

 We use the class keyword followed by the class name Book.


 Inside the class, we define properties like title and author (public in this case, allowing access
from outside).
 We also define a method called greetReader that displays a welcome message with the book's title
and author.

Now, you can create an object (instance) of the Book class. Here's how to create an object:

$book1 = new Book(); // Create an object named $book1

// Set the object's properties (like filling details of a book)


$book1->title = "Alice in Wonderland";
$book1->author = "Lewis Carroll";

// Call the object's method to greet the reader


$book1->greetReader();
 We use the new keyword followed by the class name Book to create a new object.
 We assign this object to a variable named $book1.
 Then, we use the arrow operator (->) to access the object's properties and set their values. We set
the title and author for $book1.
 Finally, we call the greetReader method on the $book1 object using the arrow operator. This will
print the welcome message specific to the book details stored in $book1.

Running this code will output:

Constructor and Destructor

Constructors and destructors are special methods used in object-oriented programming (OOP) to manage
the lifecycle of an object in PHP.

Constructors:

 PHP allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.

 A constructor is a special method with the same name as the class (often denoted by __construct).
 It's called automatically whenever a new object of that class is created using the new keyword.
 The primary purpose of a constructor is to:
 Initialize the object's properties with starting values.
 Perform any other necessary setup tasks for the newly created object.

Destructors:

 PHP possesses a destructor concept similar to that of other object-oriented languages, such as
C++. The destructor method will be called as soon as there are no other references to a particular
object, or in any order during the shutdown sequence.
 A destructor is a special method with the name __destruct.
 It's called automatically when an object goes out of scope or when the script execution ends.
 The main purpose of a destructor is to:
 Release resources associated with the object (e.g., closing files, database connections).
 Perform any necessary cleanup tasks before the object is destroyed.

Example:
<?php
class Circle { Output:
public $radius;
function __construct($radius=5){
echo "In Constructor <br>";
$this->radius = $radius;
}

function __destruct(){
echo "in Desctuctor <br>";
}

function get_Area() {
return pi() * pow($this->radius, 2);
}

function get_Circumference() {
return 2 * pi() * $this->radius;
}
}
$circle1 = new Circle();
$circle = new Circle(15);
echo "Area: " . $circle->get_Area() . "</br>";
echo "Circumference: " . $circle-
>get_Circumference() . "</br>";
echo "Area: " . $circle1->get_Area() . "</br>";
echo "Circumference: " . $circle1-
>get_Circumference() . "</br>";
?>
Explanation:
In the above example code, a class Circle is defined with
Property:
public $radius;: Declares a public property called radius.
Methods:
function get_Area()
Defines a method called get_Area.
Calculates the area of the circle and returns the result.
function get_Circumference()
Defines a method called get_Circumference.
Calculates the circumference of the circle and returns the result.
Constructors and Destructors
function __construct($radius=5)
Defines a special method called the constructor (__construct).
Sets a default value of 5 for the radius parameter.
If you don't provide a value when creating a Circle object, the radius will be set to 5.
function __destruct()
Defines a destructor (__destruct).
$circle1 = new Circle()
Creates a new Circle object named $circle1. Since no value is provided for the radius in the constructor
call, the default value of 5 is used.
$circle = new Circle(15);: Creates another Circle object named $circle, but this time providing a value of
15 for the radius.
echo "Area: " . $circle->get_Area() . "</br>";: Calculates and displays the area of the $circle object
(radius 15) using the get_Area method.
echo "Circumference: " . $circle->get_Circumference() . "</br>";: Calculates and displays the
circumference of the $circle object using the get_Circumference method.
The same is repeated for $circle1 to display its area and circumference using the default radius of 5.

Overloading
In PHP, overloading refers to the ability to dynamically create properties and methods in an object at
runtime.
Overloading allows defining methods and properties that can be accessed as if they were declared within
the class, even though they are added dynamically.
This can be useful for creating more flexible and dynamic classes.
In PHP, method overloading is not supported in the same way as in some other programming languages
like Java or Python.
Overloading can be achieved in PHP using magic methods, which are special methods with predefined
names that are automatically invoked in certain situations.
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.

Types of Overloading in PHP:


Property Overloading: Dynamically adding properties to an object.
Method Overloading: Dynamically creating methods in an object.

Magic Methods for Overloading:

__get($property) __get() is utilized for reading data from inaccessible (protected


or private) or non-existing properties.
Called when an inaccessible property is accessed.
__set($property, $value) __set() is run when writing data to inaccessible (protected or
private) or non-existing properties. Called when an
inaccessible property is set.
__isset($property) __isset() is triggered by calling isset() or empty() on
inaccessible (protected or private) or non-existing properties.
Called when isset() or empty() is called on an inaccessible
property
__unset($property) __unset() is invoked when unset() is used on inaccessible
(protected or private) or non-existing properties.
Called when unset() is called on an inaccessible property.
__call($method, $arguments) __call() is triggered when invoking inaccessible methods in an
object context.
Called when an inaccessible method is invoked.
__callStatic($method, $arguments) __callStatic() is triggered when invoking inaccessible methods
in a static context.
Called when an inaccessible static method is invoked.

Example of Property Overloading:


class DynamicProperties {
private $data = array();
// __get magic method for property overloading
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
} else {
return null;
}
}

// __set magic method for property overloading


public function __set($name, $value) {
$this->data[$name] = $value;
}
}

$obj = new DynamicProperties();


$obj->name = "";
echo $obj->name;
echo "<br>";
$obj->name = "Aditi"; // Setting a property dynamically
echo $obj->name; // Getting a property dynamically
In the property overloading example, __get() and __set() magic methods are defined to handle getting and
setting of dynamic properties, respectively. When a property is accessed or assigned on an object of the
DynamicProperties class, these magic methods are invoked to handle the operation dynamically.

Example for method overloading:

class DynamicMethods {
// __call magic method for method overloading
public function __call($name, $arguments) {
if ($name == 'dynamicMethod') {
if (count($arguments) == 1) {
echo "Hello, ".$arguments[0]."!";
} elseif (count($arguments) == 2) {
echo "Sum of ".$arguments[0]." and
".$arguments[1]." is: ".($arguments[0] + $arguments[1]);
}
}
}
}

$obj = new DynamicMethods();


$obj->dynamicMethod("John"); // Invoking a method
dynamically
echo "<br>";
$obj->dynamicMethod(5, 3); // Invoking a method
dynamically with arguments

In the method overloading example, __call() magic method is defined to handle method calls that are not
defined in the class explicitly. Depending on the method name and number of arguments, different
behaviors are implemented dynamically.
What are magic methods in php
In PHP, magic methods are predefined methods that have special names prefixed with two underscores
(__). These methods are automatically invoked by PHP when certain actions occur within a class. They
allow you to hook into the object lifecycle or handle various operations in a more controlled manner.
Magic methods provide a powerful way to customize the behavior of PHP classes and objects, allowing
you to implement various features such as method overloading, property access control, serialization, and
more.

Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class (subclass or
derived class) inherits properties and methods from another class (superclass or base class). This allows
you to create a hierarchy of classes where subclasses can reuse and extend the functionality of their parent
class.

<?php
// Parent class
class Animal {
protected $name;
protected $sound;

public function __construct($name, $sound) {


$this->name = $name;
$this->sound = $sound;
}

public function makeSound() {


echo "{$this->name} says {$this->sound}.<br>";
}
}

// Child class inheriting from Animal


class Dog extends Animal {
public function wagTail() {
echo "{$this->name} wags its tail.<br>";
}
}

// Child class inheriting from Animal


class Cat extends Animal {
public function purr() {
echo "{$this->name} purrs.\n";
}
}

// Create instances of child classes


$dog = new Dog("Buddy", "Woof");
$cat = new Cat("Whiskers", "Meow");

// Call methods from the parent class


$dog->makeSound(); // Output: Buddy says Woof.
$cat->makeSound(); // Output: Whiskers says Meow.
// Call methods specific to each child class
$dog->wagTail(); // Output: Buddy wags its tail.
$cat->purr(); // Output: Whiskers purrs.
?>

In the above example, we have a parent class Animal which has properties $name and $sound along with
a constructor to initialize them.
The Animal class also has a method makeSound() which outputs the sound the animal makes.
Then, we have two child classes: Dog and Cat, which inherit from the Animal class using the extends
keyword. This means they inherit the properties and methods of the Animal class.
Each child class can also have its own additional properties and methods, like wagTail() for Dog and
purr() for Cat.
When instances of Dog and Cat are created, they can access both the methods defined in their own class
(wagTail() and purr()) as well as those inherited from the Animal class (makeSound()).
Inheritance allows for code reusability and the creation of a hierarchy of classes, making the code more
organized and easier to maintain.

You might also like