In PHP, the keywords public, private and protected are known as the access modifiers. These keywords control the extent of accessibility or visibility of the class properties and methods. One of these keywords is prefixed while declaring the member variables and defining member functions. Whether the PHP code has free access to a class member, or it is restricted from getting access, or it has a conditional access, is determined by these keywords − The principle of data encapsulation is the cornerstone of the object-oriented programming methodology. It 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. To implement encapsulation, data members of a class are made private and the methods are made public. 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. Open Compiler It will produce the following output − 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. Output Now, the getTitle() and getPrice() functions are public, able to access the private member variables title and price. But, while trying to display the title and price directly, an error is encountered as they are not public. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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. Let us set the title member in Book class example to protected, leaving price to private. PHP allows the both the member variables to be accessed, as the object belongs to the same class. Let us add a mybook class that inherits the Book class − whose object is still able to access the member variables, as the child class inherits public and protected members of the parent class. However, make mybook class as an independent class (not extending Book class) and define a getmytitle() function that tries to access protected title member variable of Book class. As the getmytitle() function tries to print title of Book object, an error message showing Cannot access protected property Book::$title is raised. Example Try to run the following code − Open Compiler It will produce the following output − Hence, it can be seen that the protected member is accessible by object of same class and inherited class only. For all other environment, protected members are not accessible. The accessibility rules can be summarized by the following table −
Constructor and Destructor
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. 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 Open Compiler It will produce the following output − 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 − To initialize the object, pass values to the parameters inside a parenthesis in the declaration. Example Now, you can have each object with different values to the member variables. Open Compiler It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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 − 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. It will produce the following output − Type Declaration in Constructor Since PHP (version 7.0 onwards) allows scalar type declarations for function arguments, the __construct() function may be defined as − 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. 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 − As the program exits, the following output will be displayed −
Classes and Objects
The concept of classes and objects is central to PHP’s object-oriented programming methodology. A class is the template description of its objects. It includes the properties and functions that process the properties. An object is the instance of its class. It is characterized by the properties and functions defined in the class. Defining a Class in PHP To define a class, PHP has a keyword “class“. Similarly, PHP provides the keyword “new” to declare an object of any given class. The general form for defining a new class in PHP is as follows − The keyword class is followed by the name of the class that you want to define. Class name follows the same naming conventions as used for a PHP variable. It is followed by a pair of braces enclosing any number of variable declarations (properties) and function definitions. Variable declarations start with another reserved keyword 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. Functions inside a class are also called methods. Example Here is an example which defines a class of Book type − The pseudo-variable $this is available when a method is called from within an object context. $this refers to the calling object. The Book class has two member variables (or properties) – $title and $price. The member variables (also sometimes called instance variables) usually have different values for each object; like each book has a title and price different from the other. The Book class has functions (functions defined inside the class are called methods) setTitle() and setPrice(). These functions are called with reference to an object and a parameter, used to set the value of title and price member variables respectively. The Book class also has getTitle() and getPrice() methods. When called, they return the title and price of the object whose reference is passed. Once a class is defined, you can declare one or more objects, using new operator. The new operator allocates the memory required for the member variables and methods of each object. Here we have created two objects and these objects are independent of each other and they will have their existence separately. Each object has access to its member variables and methods with the “->” operator. For example, the $title property of b1 object is “$b1->title” and to call setTitle() method, use the “$b1->setTitle()” statement. To set the title and price of b1 object, Similarly, the following statements fetch the title and price of b1 book − Example Given below is the complete PHP script that defines Book class, declares two objects and calls the member functions. Open Compiler It will produce the following output −
Programming in PHP
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. Defining PHP Classes The general form for defining a new class in PHP is as follows − Here is the description of each line − Example Here is an example which defines a class of Books type − The variable $this is a special variable and it refers to the same object ie. itself. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. 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. 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. Now you call another member functions to get the values set by in above example − This will produce the following result − 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. Now we don’t need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below − This will produce the following result − Destructor Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor. Inheritance PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows − The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics − Following example inherit Books class and adds more functionality based on the requirement. Now apart from inherited functions, class Novel keeps two additional member functions. Function Overriding Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class. In the following example getPrice and getTitle functions are overridden to return some values. Public Members Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations − Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected. Private members By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class. A class member can be made private by using private keyword infront of the member. When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private. Protected members A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member. Here is different version of MyClass − Interfaces Interfaces are defined to provide a common function names to the implementers. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers. As of PHP5, it is possible to define an interface, like this − Then, if another class implemented that interface, like this − Constants A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change. Declaring one constant is easy, as is done in this version of MyClass − In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant’s name does not have a leading $, as variable names do. Abstract Classes An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this − When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same visibility. Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class. Static Keyword Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static
Listing Files
Windows command DIR and Linux command ls both display the list of files in the current directory. These commands can be operated with different switches to apply conditions on the list of files displayed. PHP provides a couple of options for programmatically listing files in a given directory. The readdir() Function The opendir() function in PHP is similar to fopen() function. It returns handles to the directory so that the contents of the directory can be read from in a serialized manner. This function opens up a directory handle to be used in the subsequent closedir(), readdir(), and rewinddir() calls. The readdir() function reads the next available entry from the stream handle returned by opendir() function. Here, dir_handle is the directory handle previously opened with opendir().not specified, the last link opened by opendir() is assumed. The closedir() function is similar to fclose() function. It closes the directory handle. The function closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir(). Example The following PHP code reads one file at a time from the currently logged directory. The scandir() Function The scandir() function retrieves the files ans subdirectories inside a given directory. The “sorting_order” by default is alphabetical in ascending order. If this optional parameter is set to SCANDIR_SORT_DESCENDING, then the sort order becomes alphabetical in descending order. If it is set to SCANDIR_SORT_NONE, then the result becomes unsorted. Example With the following PHP code, the scandir() function returns an array of files in the given directory. It will produce the following output − You can use a foreach loop to traverse the array returned by the scandir() function. It will produce the following output −
Create Directory
Computer files are stored in the local storage device (called drive) in a hierarchical order, where a directory contains one or more files as well as subdirectories. Respective DOS commands defined in operating systems Windows, Linux etc. are used to create and manage directories. PHP provides directory management functions to create a directory, change the current directory and remove a certain directory. This chapter discusses the usage of the following directory functions in PHP − The mkdir() Function The mkdir() function creates a new directory whose path is given as one of the parameters to the function Parameters Each digit is the sum of values for each type of permission − The default value of $permissions parameters is 0777, which means the directory is created with execute, write and read permissions enabled. Note that the $permissions parameter is ignored when working on Windows OS. The mkdir() function returns either true or false, indicating if the function has been successfully executed or not. Examples Here are some examples of mkdir() function. The following call to mkdir() creates a subdirectory inside the current working directory. The dot indicates that the path is relative. We can give the string parameter that contains the absolute path of the directory to be created. The following call to mkdir() contains nested directory structure inside the current directory, as the $recursive parameter is set to true. $dirs=”./dir1/dir2/dir3/”;mkdir($dirs,0777,true); The Windows explorer will show the nested directory structure as follows − The chdir() Function The chdir() function in PHP corresponds to the chdir or cd command in Linux/Windows. It causes the current directory to be changed as required. The string parameter to this function is either an absolute or relative path of a directory to which the current directory needs to be changed to. It returns true or false. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. The getcwd() Function The getcwd() function works similar to pwd command in Ubuntu Linux, and returns the path to the current working directory. Example With the following code snippet, PHP displays the current working directory before and after changing the current working directory. A couple of files are created inside the new current directory. With the scandir() function, the files are listed. It will produce the following output − The rmdir() Function The rmdir() function removes a certain directory whose path is given as parameter. The directory to be removed must be empty.
File Permissions
The concept of permissions is at the core of Unix/Linux file system. The permissions determine who can access a file and how one can access a file. File permissions in Linux are manipulated by the chmod command, which can be run inside the Linux terminal. PHP provides the chmod() function with which you can handle file permissions programmatically. PHP’s chmod() function is effective only when you are working on a Linux OS. It doesn’t work on Windows, as Windows OS has a different mechanism of controlling file permissions. To view the permissions enabled on a file, obtain the list of files using the “ls -l” command (long listing) The first column contains permission flags of each file. Third and fourth columns indicate the owner and group of each file, followed by size, date and time, and the file name. The permissions string has ten characters, their meaning is described as follows − Position Meaning 1 “d” if a directory, “-” if a normal file 2, 3, 4 read, write, execute permission for user (owner) of file 5, 6, 7 read, write, execute permission for group 8, 9, 10 read, write, execute permission for other (world) The characters in the permission string have following meaning − Value Meaning – Flag is not set. r File is readable. w File is writable. For directories, files may be created or removed. x File is executable. For directories, files may be listed. If you consider the first entry in the above list − The “a.out” file is owned by the user “mvl” and group “mvl”. It is a normal file with “read/write/execute” permissions for the owner, and “read/ execute” permissions for the group as well as others. The binary and octal representation of permission flags can be understood with the following table − Octal Digit Binary Representation (rwx) Permission 0 000 none 1 001 execute only 2 010 write only 3 011 write and execute 4 100 read only 5 101 read and execute 6 110 read and write 7 111 read, write, and execute (full permissions) The chmod() Function The chmod() function can change permissions of a specified file. It returns true on success, otherwise false on failure. The chmod() function attempts to change the mode of the specified file ($filename) to that given in permissions. The second parameter $permissions is an octal number with four octal digits. The first digit is always zero, second specifies permissions for the owner, third for the owner’s user group and fourth for everybody else. Each digit is the sum of values for each type of permission. 1 Execute Permission 2 Write Permission 4 Read Permission The default value of $permissions parameters is 0777, which means the directory is created with execute, write and read permissions enabled. Example Take a look at the following example − The chown() Function The chown() function attempts to change the owner of the file filename to a new user. Note that only the superuser may change the owner of a file. Example Take a look at the following example − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. The chgrp() Function The chgrp() function attempts to change the group of the file filename to group. Only a superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member. Example Take a look at the following example − It will produce the following output −
Handle CSV File
Popular spreadsheet programs use the CSV file format (which stands for Comma Separated Values) to export worksheet data in plain text. Each line in the file represents one row of the worksheet, with values in each column separated by commas. PHP’s filesystem function library provides two functions – fgetcsv() and fputcsv() – respectively to read data from a CSV file into an array and put the array elements in a CSV file. The fgetcsv() Function The getcsv() function reads the line from the file pointer, and parses it into CSV fields. The $stream parameter is a handle to the file resource, opened in read mode. The default separator symbol to parse the fields is comma, you can specify any other symbol if required. The fgetcsv() function returns an indexed array containing the fields. If the function encounters any error, it returns false. To demonstrate the use of fgetcsv() function, store the following text as “hello.txt” in the current working directory. Example The following PHP code reads the CSV data from this file, and returns an array. The fields in the array are then rendered in a HTML table − It will produce the following output − Name Email Post Salary Ravishankar [email protected] Manager 40000 Kavita [email protected] Assistant 25000 Nandkumar [email protected] Programmer 30000 The fputcsv() Function Te fputcsv() function puts an indexed array with its elements separated by commas, at the current file pointer position of a CSV file. The target file must be opened in write mode. The second mandatory parameter is an array consisting of comma separated fields. As in case of fgetcsv() function, the default separator is comma. Example In the following code, a two dimensional array of comma separated values is written into a CSV file. The “employee.csv” file should be created in the current working directory, after the above program is executed.
Delete File
PHP doesn’t have either a delete keyword or a delete() function. Instead, it provides the unlink() function, which when called, deletes a file from the filesystem. It is similar to Unix/C unlink function. If the delete operation could not be completed, PHP returns false and shows an E_WARNING message. The mandatory string parameter to unlink() function is a string that refers to the file to be deleted. Example The following code demonstrates a simple use of the unlink() function − Deleting the Symlink to a File The unlink() function can also delete a symlink to a file. However, deleting a symlink doesn’t delete the original file. A symlink is a shortcut to an existing file. In Windows, open a command prompt with administrator privilege and use the mlink command with /h switch to create a symlink to a file. (/j switch is used for symlink to a folder) In Ubuntu Linux, to create a symbolic link to a file, you would use the following command − To create a symbolic link to a directory, you would use the following command − In PHP, there is also a symlink() function for the purpose. Example Create a symlink with the following code − Now delete the symlink created above − If you check the current working directory, the symlink will be deleted, leaving the original file intact. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. How to Rename a File in PHP You can change the name of an existing file with the help of respective command from the console of an operating system. For example, the “mv command in Linux terminal or the “rename command” in Windows command prompt helps you to change the name of a file. However, to rename a file programmatically, PHP’s built-in library includes a rename() function. Here is the syntax of the rename() function − Both $from and $to strings are the names of files, existing and new respectively. The rename() function attempts to rename $from to $to, moving it between directories if necessary. If you are renaming a file and $to already exists, then it will be overwritten. If you are renaming a directory and $to exists, then this function will emit a warning. To change the name of “hello.txt” to “test.txt” − You can also employ a little indirect approach for renaming a file. Make a copy of an existing file and delete the original one. This also renames “hello.txt” to “test.txt” −
Append File
In PHP, the fopen() function returns the file pointer of a file used in different opening modes such as “w” for write mode, “r” read mode and “r+” or “r+” mode for simultaneous read/write operation, and “a” mode that stands for append mode. When a file is opened with “w” mode parameter, it always opens a new file. It means that if the file already exists, its content will be lost. The subsequent fwrite() function will put the data at the starting position of the file. Assuming that a file “new.txt” is present with the following contents − The following statement − Erases all the existing data before new contents are written. Read/Write Mode Obviously, it is not possible to add new data if the file is opened with “r” mode. However, “r+” or “w+” mod opens the file in “r/w” mode, but still a fwrite() statement immediately after opening a file will overwrite the contents. Example Take a look at the following code − With this code, the contents of the “new.txt” file will now become − To ensure that the new content is added at the end of the existing file, we need to manually put the file pointer to the end, before write operation. (The initial file pointer position is at the 0th byte) The fseek() Function PHP’s fseek() function makes it possible to place the file pointer anywhere you want − The $whence parameter is from where the offset is counted. Its values are − Example So, we need to move the pointer to the end with the fseek() function as in the following code which adds the new content to the end. Now check the contents of “new.txt”. It will have the following text − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Append Mode Instead of manually moving the pointer to the end, the “a” parameter in fopen() function opens the file in append mode. Each fwrite() statement adds the content at the end of the existing contents, by automatically moving the pointer to SEEK_END position. One of the allowed modes for fopen() function is “r+” mode, with which the file performs read/append operation. To read data from any position, you can place the pointer to the desired byte by fseek(). But, every fwrite() operation writes new content at the end only. Example In the program below, the file is opened in “a+” mode. To read the first line, we shift the file position to 0the position from beginning. However, the fwrite() statement still adds new content to the end and doesn’t overwrite the following line as it would have if the opening mode “r+” mode. Thus, we can append data to an existing file if it is opened in “r+/w+” mode or “a/a+” mode