PHP FUNCTIONS AND OBJECTS
PHP FUNCTIONS AND OBJECTS
AND OBJECTS
PHP Functions
PHP comes with hundreds of ready-made, built-in functions, making it a very rich
language. To use a function, call it by name. For example, you can see the date
function in action here:
phpinfo();
Displays lots of information about the current installation of PHP and requires no
argument:
Advantages of Functions
Functions have many advantages over contiguous, inline code. For example, they:
• Decrease execution time, because each function is compiled only once, no matter
• Accept arguments and can therefore be used for general as well as specific cases
PHP Functions
● A function is a set of statements that can be called by name.
○ May take arguments and return a value.
○ Built-in and user defined.
● Example 5-1. Three string functions
<?php
echo strrev(" .dlrow olleH"); // Reverse string
echo str_repeat("Hip ", 2); // Repeat string
echo strtoupper("hooray!"); // String to uppercase
?> // Hello world. Hip Hip HOORAY!
4
Defining a Function
● A definition starts with the word function followed by name (case-insensitive)
and parentheses (required).
● Name must start with a letter or underscore, followed by any number of letters,
numbers, or underscores.
● One or more optional comma separated parameters listed within parentheses.
● Statements may include one or more return statements, which force the
function to cease execution and return to the calling code.
● General syntax:
function function_name([parameter [, ...]])
{
// Statements
} 5
Returning a Value
● Example 5-2. Cleaning up a full name by converting a person’s
full name to lowercase and then capitalizing the first letter of
each part of the name.
<?php
echo fix_names("WILLIAM", "gatES");
function fix_names($n1, $n2)
{
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2)); //
return $n1 . " " . $n2 ;
}
?> 6
Returning an Array
● Example 5-3. Returning multiple values in an array
<?php
$names = fix_names("WILLIAM", "gatES");
echo $names[0] . " " . $names[1] ;
function fix_names($n1, $n2)
{
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
return array($n1, $n2); // Keeps first and last name separate
}
?> 7
Passing Arguments by Reference
● Place & symbol in front of each parameter within the function definition to pass by reference.
● Example 5-4. Passing values to a function by reference
<?php
$a1 = "WILLIAM";
$a2 = "gatES";
echo $a1 . " " . $a2 . "<br>";
fix_names($a1, $a2);
echo $a1 . " " . $a2 ;
}
?>
8
Returning Global Variables
● Example 5-5. Returning values in global variables
<?php
$a1 = "WILLIAM";
$a2 = "gatES";
echo $a1 . " " . $a2 . "<br>";
fix_names();
echo $a1 . " " . $a2 ;
function fix_names()
{
global $a1; $a1 = ucfirst(strtolower($a1));
global $a2; $a2 = ucfirst(strtolower($a2));
// Once declared global, these variables retain global access and are available to the rest of
the program
} 9
?>
Recap of Variable Scope
● Local variables are accessible just from the part of your code
where you define them.
● Global variables are accessible from all parts of your code.
● Static variables are accessible only within the function that
declared them but retain their value over multiple calls.
10
Including and Requiring Files
● The include Statement
○ Tells PHP to fetch a particular file and load all its contents.
○ Example 5-6. Including a PHP file
<?php
include "library.php";
// Your code goes here
?>
11
Including and Requiring Files
● Using include_once
○ Each time include directive is issued, it includes the requested file again.
○ This may produce error messages, because you’re trying to define the same constant or function
multiple times.
12
Including and Requiring Files
● Using require and require_once
○ Potential problem with include and include_once is that PHP will only attempt to include the
requested file. Program execution continues even if the file is not found.
13
Recursive Functions
A recursive function in PHP is a function that calls itself in order to solve a
problem. This technique is commonly used in situations where a problem can be
broken down into smaller, similar sub-problems.
Base Case: Every recursive function should have a base case, which is a
condition that stops the recursion. Without a base case, the function will keep
calling itself indefinitely, leading to a stack overflow error.
function recursiveFunction($input) {
if ($input <= 0) {
return 0;
}
return $input + recursiveFunction($input - 1);
}
echo recursiveFunction(5);
Remember the Call Stack: When a function calls itself, each call is added to the
call stack. You should be cautious about stack depth to avoid running into a stack
overflow error.
Tail Recursion: PHP does not optimize tail recursion (a specific type of recursion
where the recursive call is the last thing in the function). In some cases, this can
lead to stack overflow errors. If optimization is a concern, consider using iterative
solutions
Recursive Functions vs. Iterative Solutions: Recursive functions can be less
efficient and harder to debug than their iterative counterparts. Use recursion when
it simplifies the problem-solving process or when it's a natural fit.
.Handling Large Inputs: Recursive functions can be slow for large inputs due to
the overhead of function calls. Consider using memoization (caching previously
computed results) or dynamic programming for optimization in such cases.
Maintain a Clear Exit Strategy: Always ensure that your recursive function is
designed with a clear base case and a way to make progress toward that base
case.
Assignment
1. Print Multiplication Table of 73 till 12 times Using recursion.
2. Factorial Calculation Using Recursion.
3. Fibonacci Sequence Using Recursion.
4. Given a string S, print the count of all contiguous substrings that
start and end at the same character.
For Example:
Input : S = "abca"
Resultant Strings : { "a", "b", "c", "a", "abca" }
Output : 5
PHP Objects
● When creating a program to use objects, you need to design a
composite of data and code called a class.
● Objects based on class are called an instance(s) of that class.
● The data associated with an object is called its properties and
functions it uses are called methods.
17
Declaring a Class
● Define a class with the class keyword.
● Definition contains the class name (which is case-sensitive), its properties, and its methods.
19
Accessing Objects
● Example 5-11. Creating and interacting with
an object class User
<?php {
$object = new User;
public $name, $password;
print_r($object); echo "<br>";
$object->name = "Joe"; function save_user()
$object->password = "mypass"; {
print_r($object); echo "<br>"; echo "Save User code goes here";
$object->save_user(); }
}
?>
// User Object ( [name] => [password] => )
User Object ( [name] => Joe [password] => mypass )
Save User code goes here
20
Cloning Objects
●An object is passed by reference when you pass it as a
parameter.
●Example 5-12. Copying an object?
<?php
$object1 = new User(); $object1->name = "Alice";
$object2 = $object1; $object2->name = "Amy";
echo "object1 name = " . $object1->name . "<br>";
echo "object2 name = " . $object2->name;
class User
{ public $name;
} //object1 name = Amy
?> //object2 name = Amy
21
Cloning Objects
● The clone operator creates a new instance of the class and
copies the property values from the original instance to the
new instance.
● Example 5-13. Cloning an object
<?php
$object1 = new User(); $object1->name = "Alice";
$object2 = clone $object1; $object2->name = "Amy";
echo "object1 name = " . $object1->name . "<br>";
echo "object2 name = " . $object2->name;
class User
{ public $name;
} //object1 name = Alice
?> //object2 name = Amy
22
Constructors
● When creating a new object, you can pass a list of
arguments to the class being called.
● Arguments are passed to a special method within the class,
called the constructor, which initializes various properties.
● The name of the constructor method should be
“__construct” (construct preceded by two underscore
characters).
● Example 5-14. Creating a constructor method
<?php
class User
{ function __construct($param1, $param2)
{ // Constructor statements go here
public $username = "Guest";
}
} ?>
23
Destructors
● PHP destructor is called when code has made the last
reference to an object or when a script ends.
● Allows to clean up resources when object is destroyed.
● A destructor cannot accept any argument.
● Example 5-15. Creating a destructor method
<?php
class User
{ function __destruct()
{
// Destructor statements go here
}
}
?>
24
Example
<?php
class MyDestructableClass {
function __construct($name) {
echo "In constructor";
$this->name = $name;
}
function __destruct() {
echo "Destroying " . $this->name;
}
}
$obj = new MyDestructableClass(“Bubble”);
$obj=NULL;
?> 25
Writing Methods
● Declaring a method is similar to declaring a function.
● Method names beginning with a double underscore (__) are
reserved.
● A special variable called $this is used to access the current
object’s properties.
26
Using the variable $this in a method
<?php
class User
{
public $name, $password;
function get_password(){
return $this->password;
}
}
$object = new User;
$object->password = "secret";
echo $object->get_password();
?> 27
Static Methods
● A static method is called on a class itself, not on an object.
● A static method has no access to any object properties.
● Call the class, along with the static method, using a double
colon (:: scope resolution operator), not ->.
● Static functions are useful for performing actions relating to the
class itself, but not to specific instances of the class.
28
Creating and accessing a static method
<?php
User::pwd_string();
class User
{
static function pwd_string()
{
echo "Please enter your password";
}
}
?>
29
Declaring Properties
● Properties within classes can be implicitly defined when first
used.
○ PHP implicitly declares the variables for you.
● Implicit declarations can lead to bugs that are difficult to
discover, because name was declared from outside the class.
● Always declare properties explicitly within classes.
● A property within a class can be assigned a default value to it.
● The value must be a constant and not the result of a function
or expression.
30
Defining a property implicitly
<?php
$object1 = new User();
$object1->name = "Alice";
echo $object1->name;
class User {}
?>
31
Valid and invalid property declarations
<?php
class Test
{
public $name = "Paul Smith"; // Valid
public $age = 42; // Valid
public $time = time(); // Invalid - calls a function
public $score = $level * 2; // Invalid - uses an expression
}
?>
32
Declaring Constants
●Once defined constant cannot be changed.
●Constants inside classes can be defined using const
keyword.
●General practice is to use uppercase letters.
●Constants can be directly referenced using the self keyword
and scope resolution operator (::).
33
Defining constants within a class
<?php
Translate::lookup();
class Translate
{
const ENGLISH = 0;
const SPANISH = 1;
const FRENCH = 2;
const GERMAN = 3;
// ...
static function lookup()
{
echo self::SPANISH;
}
}
?> 34
Property and Method Scope
● public
○ These properties are the default when you are declaring a variable or when a variable is implicitly
declared the first time it is used.
○ Methods are assumed to be public by default.
● protected
○ These properties and methods (members) can be referenced only by the object’s class methods
and those of any subclasses.
● private
○ These members can be referenced only by methods within the same class—not by subclasses.
35
Property and Method Scope
●How to decide which to use:
○Use public when outside code should access this
member and extending classes should also inherit it.
○Use protected when outside code should not access this
member but extending classes should inherit it.
○Use private when outside code should not access this
member and extending classes also should not inherit it.
36
Changing property and method scope
<?php
class Example
{
var $name = "Michael"; // Same as public but deprecated
public $age = 23; // Public property
protected $usercount; // Protected property
private function admin() // Private method
{
// Admin code goes here
}
}
?> 37
Static Properties and Methods
● Most data and methods apply to instances of a class.
● But occasionally you’ll want to maintain data about a whole
class.
○ For instance, to report how many users are registered, you will store a variable that applies to the
whole User class.
38
Defining a class with a static property
<?php
$temp = new Test();
echo "Test A: " . Test::$static_property . "<br>";
echo "Test B: " . $temp->get_sp() . "<br>";
echo "Test C: " . $temp->static_property . "<br>";
class Test {
static $static_property = "I'm static";
function get_sp(){
return self::$static_property;
}
}
?> 39
Defining a class with a static property
● Output:
Test A: I'm static
Test B: I'm static
Notice: Undefined property: Test::$static_property
Test C:
● The property $static_property could be directly referenced from
the class itself via the double colon operator in Test A.
● Test B could obtain its value by calling the get_sp method of
the object $temp, created from class Test.
● Test C failed, because the static property $static_property was
not accessible to the object $temp.
40
Inheritance
● Once you have written a class, you can derive subclasses from
it.
● You can take a class similar to the one you need to write,
extend it to a subclass, and just modify the parts that are
different. You achieve this using the extends operator.
● The final keyword can be used to prevent class inheritance.
41
Inheriting and extending a class
<?php
$object = new Subscriber;
$object->name = "Fred";
$object-> pswd = "pword";
$object->phone = "012 345 6789";
$object->email = "[email protected]";
$object->display();
class User
{
public $name, $pswd;
function save_user()
{echo "Save User code goes here";}
}
44
Overriding a method and using the parent
operator
<?php
$object = new Son;
$object->test();
$object->test2();
class Dad {
function test() {
echo "[Parent Class] <br>";
}
}
class Son extends Dad{
function test() {
echo "[Child Class]<br>";
}
function test2() {
parent::test();
}
}
?>
45
Overriding a method and using the parent
operator
● Create a class called Dad and its subclass called Son that
inherits its properties and methods.
● Then override the method test.
● The only way to execute the overridden test method in the Dad
class is to use the parent operator.
● The code outputs the following:
[Child Class]
[Parent Class]
46
Subclass constructors
● PHP will not automatically call the constructor method of the
parent class.
● Subclasses should always call the parent constructors to
execute all the initialization code.
47
Calling the parent class constructor
<?php class Wildcat class Tiger extends Wildcat
$object = new Tiger(); { {
echo "Tigers have...<br>"; public $fur; // public $stripes; // Tigers
echo "Fur: " . $object->fur . Wildcats have fur have stripes
"<br>"; function function __construct()
echo "Stripes: " . __construct() {
{
$object->stripes; $this->fur =
// Call parent constructor
"TRUE";
first
}
parent::__construct();
}
$this->stripes = "TRUE";
}
}
?>
48
Calling the parent class constructor
● The Wildcat class has created the property $fur, which we’d
like to reuse, so we create the Tiger class to inherit $fur and
additionally create another property, $stripes.
● To verify that both constructors have been called, the program
outputs the following:
Tigers have...
Fur: TRUE
Stripes: TRUE
49
Final methods
● Use final keyword before method definition to prevent a
subclass from overriding a superclass method.
● Example:
<?php
class User
{
final function copyright()
{
echo "This class was written by Joe Smith";
}
}
?>
50
Assignment Exercise #1
Write a program to check if a string is a palindrome in PHP, you can create a function that
compares the original string with its reverse. If they match, the string is a palindrome.
Assignment Exercise #2
Exercise Description:
Write a PHP program to find the factorial of a number using a recursive function.
Assignment Exercise #4
Write a function that calculates the sum of the first N numbers in the Fibonacci
sequence. The Fibonacci sequence is defined as follows:
● The first two numbers are 0 and 1.
● The next numbers are the sum of the two preceding ones: F(n) = F(n-1) + F(n-2).
Your task is to implement a function fibonacciSum(N) that takes an integer N as input
and returns the sum of the first N numbers in the Fibonacci sequence.
Constraints:
fibonacciSum(5);
● 1 <= N <= 100
7
# The first 5 Fibonacci numbers are: 0, 1, 1, 2, 3.
# Their sum is 0 + 1 + 1 + 2 + 3 = 7.
Assignment Exercise #5
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8,
and -2.7335 would be truncated to -2.
Example 1:
Example 2:
Given a string S, print the count of all contiguous substrings that start and
end at the same character.
For Example:
Input : S = "abca"
Resultant Strings : { "a", "b", "c", "a", "abca" }
Output : 5
Assignment Exercise #7
Create a class name Product and create a instance of that class name product1.
Add properties (name, description and price) to the class Product. A little hint. We create
properties like we create a variable but the property needs to have an access modifier prefix:
public, private or protected. For now use the public prefix.
After that go to the instantiated object product1 and modify the property name for 'iPhone 12'.
Then you can: echo product1->name to see the result.
create a second object named product2 and set its name property to 'Samsung F12' and echo out
that property.
Assignment Exercise #8
Examples
$circy = new Circle(11);
$->getArea();