Classes and Object2.1
Classes and Object2.1
2
Introduction
• A class can have properties, which are variables that store data, and methods,
which are functions that perform actions on the object. Classes can also have
constructors, which are special methods that are called when an object is
created, and destructors, which are special methods that are called when the
object is destroyed.
3
PHP: Creating classes and Instantiation
• A class is defined by using the class keyword, followed by the name of the class
and a pair of curly braces ({}). All its properties and methods go inside the braces:
Syntax:-
<?php
class Class_name {
}
?>
4
Cntd..
Below we declare a class named Fruit consisting of two properties ($name
and $color) and two methods set_name() and get_name() for setting and
getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
5
?>
Key Concepts
Properties and Methods
• Properties: Variables defined inside a class. Use $this->propertyName to access
properties within the class.
• Methods: Functions defined inside a class. They define the behavior of the
object.
Access Modifiers
• public: Can be accessed from anywhere.
• protected: Can be accessed within the class and by derived classes.
• private: Can only be accessed within the class.
6
Key Concepts
Types of Methods
1.Instance Methods
These methods are accessed through the object of a class.
class Car {
public function drive()
{
echo "The car is driving";
}}
$myCar = new Car();
$myCar->drive(); // Output: The car is driving
7
Key Concepts
2. Static methods
Static methods are associated with the class rather than any object. Use the
static keyword, and access them with the :: operator.
class Math {
public static function square($num)
{
return $num * $num;
}
}
echo Math::square(4); // Output: 16
8
$ this Keyword
$ this keyword refers to the present object, and this keyword can only
be used inside a member function of a class. We can use $ this keyword
in two ways
• 1) To add a value to the declared variable, we have to use $ this
property inside the (set _ name) function
• 2) In order to add a value to declared variable, the property of
variable can be changed directly.
• ->
<?php $employee_1 = new employee();
class employee { $employee_1->set_name("JOHN");
public $name; $employee_1->set_salary(" $ 2000000");
var $salary; $employee_2 = new employee();
function set_name($name) { $employee_2->set_name("ROCK");
$this->name = $name; $employee_2->set_salary(" $ 1200000");
} echo $employee_1->name;
function set_salary($salary) { echo $employee_1->salary;
$this->salary = $salary; echo "<br>";
} echo $employee_2->name;
} echo $employee_2->salary;
?>
Define Objects
• The object is declared to use the properties of a class.
• The object variable is declared by using the new keyword followed by the
class name.
• Multiple object variables can be declared for a class.
• The object variables are work as a reference variable. So, if the property
value of any class is modified by one object then the property value of
another object of the same class will be changed at a time.
Syntax:
11
Creating an Object:
class Books {
// Members of class Books
}
// Creating three objects of Books
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Example
<?php
function getTitle(){
class Books {
echo $this->title."<br>" ;
}
/* Member variables */
}
var $price;
var $title;
/* Creating New object using "new"
operator */
/* Member functions */
$maths = new Books;
function setPrice($par){
$this->price = $par;
/* Setting title and prices for the
}
object */
$maths->setTitle( "Algebra" );
function getPrice(){
$maths->setPrice( 7 );
echo $this->price."<br>";
}
/* Calling Member Functions */
$maths->getTitle();
function setTitle($par){
$maths->getPrice();
$this->title = $par;
?>
}
PHP File Handling
• File handling is the process of interacting with files on the server, such as
reading file, writing to a file, creating new files, or deleting existing ones. File
handling is essential for applications that require the storage and retrieval of
data, such as logging systems, user-generated content, or file uploads.
• It is used when you need to store data persistently or handle files uploaded by
users. PHP provides several built-in functions to make file handling easy and
secure.
14
PHP File Handling
• PHP has many functions to work with normal files. Those functions are:
1) fopen()
2)fread()
3) fwrite()
4) fclose()
15
PHP Open File/Create File - fopen()
• The PHP fopen() function is used to open a file.
• The fopen() function is also used to create a file
• When opening a file, there are several different modes you can use.
• The most common ones are r and w for read and write.
• There are several more available though that will control whether you create a new file, open an
existing file, and whether you start writing at the beginning or the end.
• Example:-
<?php
$file = fopen(“demo.txt”,'w');
?>
16
File handling in PHP
Once you’re done working with the file, you should close it using fclose() to free up
resources.
<?php
if ($file) {
echo "File opened successfully!";
fclose($file); // Close the file
} else {
echo "Failed to open the file.";
}
17
• ?>
Modes
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
18
Fread()
• fread() –– After file is opened using fopen() the contents of data are
read using fread(). It takes two arguments. One is file pointer and
another is file size in bytes, e.g.,
<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>
fwrite()
• fwrite() – New file can be created or text can be appended to an
existing file using fwrite() function. Arguments for fwrite() function
are file pointer and text that is to written to file. It can contain
optional third argument where length of text to written is specified,
e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
fclose()
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
PHP Directory
• The directory functions allow you to retrieve information about directories and their contents.
• PHP Directory Functions
Function Description
chdir() Changes the current directory
chroot() Changes the root directory
closedir() Closes a directory handle
dir() Returns an instance of the Directory class
getcwd() Returns the current working directory
opendir() Opens a directory handle
readdir() Returns an entry from a directory handle
scandir() Returns an array of files and directories of a specified directory
22
Create a New Directory
• We use the mkdir() function to create a new directory in the PHP programming
script.
• Syntax:
mkdir(path, mode, recursive, context)
Example:
<?php
mkdir("/articles/");
echo("Directory created");
?>
23
List the Contents of a Directory
• We use opendir() and readdir() for opening the directory link and to read it
respectively. Step 1 will be to open the directory and Step 2 will be to read it.
• Step 1: To open the directory link, opendir() is the function we use to do this
step. It requires two input arguments as specified below.
Syntax:
opendir($dir_path,$context);
$dir_path is the path of the directory which needs to be opened.
$context : Optional. Specifies the context of the directory handle. Context is a set of
options that can modify the behavior of a stream
• Step 2: To read the contents of the directory, readdir() is the function which
is used for this purpose and it needs to be called recursively till the end of
the directory is reached by the directory handle.
24
Example
<?php
$direct = "/files/";
if (is_dir($direct))
{
if ($td = opendir($direct))
{
while (($file = readdir($td)) !== false)
{
echo "filename:" . $file . "<br>";
}
closedir($td);
}
}
?> 25
To Close a Directory
26
Example:
<?php
$dir = "/file1";
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
$direc = readdir($dh);
echo("File present inside directory are:" .direc);
closedir($dh);
echo("Closed directory");
}
}
?> 27
PHP Directory
28
File functions, working with directories
Certainly! Here are some common file functions and operations for working with directories in
PHP:
Creating a Directory:
mkdir($directoryPath, $mode, $recursive): Creates a new directory. The $directoryPath
parameter specifies the directory path, $mode defines the permissions (e.g., 0755), and
$recursive determines whether to create parent directories recursively if they don't exist.
Deleting a Directory:
rmdir($directoryPath): Removes an empty directory from the file system.
unlink($filePath): Deletes a file from the file system.
Checking File/Directory Information:
1. file_exists($path): Checks if a file or directory exists at the specified path. Returns true if it exists,
false otherwise.
2. is_file($filePath): Determines if a given path corresponds to a regular file. Returns true if it's a file,
false otherwise.
3. is_dir($directoryPath): Determines if a given path corresponds to a directory. Returns true if it's a
directory, false otherwise.
4. is_readable($path): Checks if a file or directory is readable. Returns true if it's readable, false
otherwise.
5. is_writable($path): Checks if a file or directory is writable. Returns true if it's writable, false otherwise.
6. Renaming/Moving a File or Directory:
7. rename($oldPath, $newPath): Renames or moves a file or directory from the old path to the new path.
8. Copying a File:
9. copy($source, $destination): Copies a file from the source path to the destination path.
These functions provide basic file and directory operations in PHP. It's worth noting that some operations,
30
like deleting non-empty directories, require additional handling, such as using recursive functions or third-
File Uploading & Downloading
• PHP File Upload
• PHP allows you to upload single and multiple files through few lines of code only.
• PHP file upload features allows you to upload binary and text files both. Moreover, you can have the full control over
the file to be uploaded through PHP authentication and file operation functions.
1. PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type,
file size,temp file name and errors associated with file.
Here, we are assuming that file name is filename.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type’]
32
• PHP File Upload Example
• File: uploadform.html
1.<form action="uploader.php" method="post" enctype="multip
art/form-data">
2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit
"/>
33
PHP File Upload Example
• File: uploadform.html
1. <form action="uploader.php" method="post" enctype="multipart/form-data">
2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit"/>
5. </form>
• File: uploader.php
1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10.?> 34
THANK YOU