Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Category: PHP

PHP

  • OO PHP

    Understanding Object-Oriented PHP

    Introduction

    Object-Oriented PHP, predominantly version 5, offers a powerful way to structure and organize code for better maintainability and reusability.

    Basic Class Structure

    class ClassName {
        // Class properties
        public $variable;
    
        // Class methods
        public function method() {}
    }
    
    $obj = new ClassName();
    $obj->method();

    The $this variable always refers to the current object being worked on.

    Access Control Modifiers

    PHP supports access control modifiers like public, private, protected, abstract, and final for defining the visibility of properties and methods within a class.

    Inheritance and Constructors

    PHP uses the extends keyword for inheritance. Constructors are defined using __construct() and destructors using __destruct(). The parent:: keyword is used to access parent class methods.

    Object Manipulation

    • Use unset() to destroy objects and trigger the destructor.
    • Cloning an object is done using clone. The process involves copying all members and calling the __clone() method.

    Polymorphism and Binding

    Polymorphism in PHP allows one interface to control access to a general class of actions. It can be achieved through compile-time polymorphism (function overloading) and run-time polymorphism (inheritance and virtual functions).

    Early binding determines the execution path at compile time, while late binding allows for dynamic execution at runtime.

    Magic Methods

    • __sleep() and __wakeup() for serialization and deserialization.
    • __autoload(classname) for autoloading classes.
    • __get(propname) and __set(key, value) for handling unknown properties.
    • __call() for handling unknown methods.
    • __toString() for converting objects to strings.

    Static Methods and Properties

    Static method calls are compiled at compile time and accessed using classname::method(). Static properties can only be accessed within static functions.

    Advanced Concepts

    • PHP provides functions like class_exists(), get_class(), and get_declared_classes() for class manipulation.
    • Overloading and overriding allow for dynamic creation of properties and methods, as well as method redefinition in derived classes.
    • Interfaces facilitate multiple inheritance and ensure implementation of all defined methods in implementing classes.
    • Traits enable code reuse across classes by grouping functions together.
    • Reflection API allows for introspection of classes, interfaces, functions, and methods, including retrieval of doc comments.

    Dereferencing and Lazy Loading

    Dereferencing in PHP involves accessing return values without assigning them to intermediate variables first. Lazy loading refers to loading classes only when needed, enhancing performance.

    Conclusion

    Object-Oriented PHP offers a robust way of structuring code, promoting reusability and maintainability through concepts like classes, inheritance, polymorphism, and advanced features like magic methods and reflection.

  • Miscellaneous

    Exploring PHP Features

    Understanding PHP Configuration

    The ini_set("param", value) function in PHP is used to dynamically set configuration options from within your PHP scripts. This function allows you to customize the behavior of PHP at runtime, overriding the settings specified in the php.ini file.

    Standard PHP Library (SPL)

    The Standard PHP Library (SPL) is an essential addition to PHP 5, offering a wide range of built-in classes and interfaces to work with data structures, iterators, and more. It exposes internal functionality of PHP, allowing developers to write objects that mimic the behavior of arrays. For instance, you can create objects that can be iterated or looped through just like arrays.

    PHP 5 Enhancements

    PHP 5 introduced several key enhancements that revolutionized the way developers write code. Some of the notable improvements include:

    • Objects passed by reference: In PHP 5, objects can be passed around by reference, allowing for more efficient memory usage and better performance.
    • Visibility in class methods and properties: PHP 5 introduced visibility keywords like public, private, and protected to control access to class members, enhancing encapsulation and security.
    • Interfaces and abstract classes: PHP 5 added support for interfaces and abstract classes, enabling better code organization and promoting code reusability through inheritance.
    • Magic methods: PHP 5 introduced a variety of magic methods like __construct, __destruct, __get, __set, etc., allowing developers to implement custom behaviors in their classes.
    • SimpleXML: PHP 5 included the SimpleXML extension, which provides an easy way to work with XML data, simplifying tasks like parsing and manipulating XML documents.
    • PDO (PHP Data Objects): PDO is a database access layer in PHP that provides a consistent interface for accessing databases. It offers enhanced security features and supports multiple database drivers.
    • Reflection: PHP 5 introduced the Reflection API, which allows developers to inspect classes, interfaces, functions, methods, and properties at runtime. This feature enables advanced introspection and dynamic code generation.

    These enhancements in PHP 5 have made it a more robust and versatile programming language, empowering developers to build complex applications with ease.

  • General

    General IT Notes on PHP Programming

    PHP Case Sensitivity

    PHP is considered partially case-sensitive. While language statements and functions are not case-sensitive, variable names are case-sensitive. For example, $variable and $VARIABLE would be treated as different entities.

    Tags in PHP

    PHP supports various tags for embedding PHP code within HTML or other documents:

    • Standard Tags: <?php ?> – These are the most commonly used tags for PHP code.
    • Short Tags: <? ?> and <?= $var ?> – Shorter alternatives to the standard tags. Note: Short tags are not always enabled in PHP configurations.
    • Script Tags: <script language="php"></script> – An older way of embedding PHP code, not commonly used now.
    • ASP Tags: <% %> – Similar to ASP style tags, supported for backward compatibility but not recommended for new code.

    Variables in PHP

    In PHP, variables are declared using the $ symbol. It is important to note the following about variables:

    • Curlies: Variables can be enclosed in curly braces like ${a} or {$a}. This is especially useful when accessing array elements within a string.
    • Quoting: Inside single quotes, variables are not directly interpolated. To include variables in strings, use double quotes instead.

    Comments in PHP

    Comments in PHP help in documenting code and are not executed by the PHP parser. PHP supports various types of comments:

    // Single line comment using double slashes.
    
    # Single line comment using hash.
    
    /* Multi-line
       comment using slash-asterisk.
    
    /**
    * API Documentation Example.
    *
    * @param string $bar
    */
    
    // Heredoc syntax for multi-line strings.
    
    <<<EOT
    ... text
    EOT;
    
    // Nowdoc syntax for multi-line strings. Introduced in PHP 5.3.0.
    
    <<<'EOT'
    ... text
    EOT;
    
    
  • Functions

    Functions in PHP

    Function Overloading in PHP

    PHP does not directly support function overloading. However, you can simulate function overloading using the __call__ magic method. This is possible because PHP functions can accept variable-length argument lists. To handle variable arguments, functions like func_num_args(), func_get_arg(), and func_get_args() can be used.

    Default Parameters

    PHP allows you to set default parameters for functions. These parameters are used when no argument is provided for that parameter during a function call.

    Global Variables

    The $GLOBALS array in PHP contains references to all variables available in the global scope. By using the global keyword, you can access global variables within a function by importing them into the local variable table.

    Variable Variables

    PHP supports variable variables, denoted by $$var. This feature enables you to dynamically create variable names and access their values.

    Super Globals in PHP

    PHP provides various superglobal arrays such as $GLOBALS, $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUEST, $_SERVER, and $_ENV. These arrays are accessible from anywhere in your PHP scripts.

    Passing Arguments by Reference

    In PHP, when passing arguments by reference, you use the ampersand (&) operator. Similarly, you can return values by reference using the ampersand operator.

    Anonymous Functions (Closures)

    Anonymous functions, also known as closures, are functions without a specified name. They can be assigned to variables and passed as arguments to other functions. In PHP, anonymous functions yield objects of the closure class.

    $area = function ($side) {
        return $side * $side;
    };
    
    echo $area(5);

    Constants in PHP

    Constants in PHP can be defined using the define() function. The syntax is define("constantname", value, true/false), where setting the third parameter to true makes the constant case-insensitive.

    • To check if a constant is defined, you can use the defined("constantname") function.
    • To retrieve the value of a constant stored in a variable or a function, you can use constant($var), where $var holds the constant name.
  • Errors and Exceptions

    Errors and Exceptions in PHP

    Error vs. Exception

    In PHP, errors and exceptions play distinct roles in the handling of issues that may arise during script execution. Errors are predefined problems that occur when the script runs, while exceptions are objects specifically designed to represent and manage errors.

    Types of Errors

    • Compile Time Errors: These errors are identified during the compilation of the code. They cannot be caught and will lead to the termination of the script if not rectified promptly.
    • Fatal Errors: Critical errors that abruptly halt the execution of the script and cannot be recovered from. These errors usually indicate severe issues in the code.
    • Recoverable Errors: Errors that can be managed within the script by implementing appropriate error-handling mechanisms. These errors allow for recovery and continuation of script execution.
    • Warnings: Warnings signal potential problems in the script but do not halt its execution. They serve as alerts for developers to investigate and address potential issues.
    • Notices: Notices provide informational messages about non-critical problems in the script without affecting its execution. These messages are typically used for debugging and optimization purposes.

    Error Reporting in PHP

    Controlling how errors are handled and displayed is crucial in PHP development. The error reporting directive in PHP allows developers to manage error visibility and logging effectively. The settings display_errors and log_errors determine whether errors are displayed on the screen and logged to a file, respectively.

    To suppress errors for a specific expression, developers can utilize the @ symbol, known as the error control operator.

    For custom error handling, developers can define a custom error handler using set_error_handler("functionName") to treat errors as exceptions and implement personalized error management logic.

    set_error_handler("customError");
    function customError($errno, $errstr) {
        // Custom error handling logic
    }

    Exceptions in PHP

    • Exception Class: In PHP, the Exception class serves as the foundation for exception handling. Developers have the flexibility to create custom exception classes by extending the base Exception class to address specific error scenarios.
    • Throwing Exceptions: To trigger an exception within a script, developers use the throw keyword to raise the exception and interrupt the normal flow of execution.
    • Exception Handling: PHP offers the capability to establish a catch-all function using set_exception_handler() to manage uncaught exceptions gracefully and provide a centralized approach to exception handling.
    function handleUncaughtException($e) {
        echo $e->getMessage();
    }
  • Design Pattern

    Design Patterns in PHP

    Introduction to Design Patterns

    Design patterns are proven solutions to common software design problems that have been implemented and refined over time. They offer a structured approach to addressing recurring design challenges, enhancing code reusability, maintainability, and scalability. Design patterns can be applied in various programming paradigms, including procedural programming and Object-Oriented Programming (OOP).

    Singleton Pattern

    The Singleton Pattern ensures that a class has only one instance globally accessible across the application. It is useful when you want to control the instantiation of a class and restrict it to a single object. In PHP, the Singleton Pattern typically involves a private constructor to prevent direct instantiation and a static method to provide access to the single instance.

    An example of applying the Singleton Pattern in PHP is in managing a database connection. By enforcing a single database connection instance, you can avoid unnecessary overhead and ensure data consistency throughout the application.

    Factory Pattern

    The Factory Pattern is a creational design pattern that delegates the responsibility of object creation to a separate factory class. This pattern enables the creation of objects without specifying their concrete classes, promoting flexibility and decoupling. By centralizing object creation logic, the Factory Pattern simplifies the process of adding new object types without modifying existing code.

    For instance, a system handling data storage can utilize the Factory Pattern to instantiate different storage classes based on user preferences. By adhering to a common interface, such as a storage interface, the factory can create diverse storage objects like INI, DB, or XML without exposing the instantiation details to the client code.

    Registry Pattern

    The Registry Pattern serves as a global store for sharing objects and data across different components of an application. It acts as a centralized repository for resources, offering a convenient way to access and manage shared objects. By utilizing the Registry Pattern, developers can simplify resource handling and enhance the accessibility of commonly used objects.

    In PHP, the Registry Pattern can be implemented to store instances of classes or configuration settings in a key-value store, facilitating easy retrieval and modification of shared resources throughout the application’s execution.

    MVC (Model-View-Controller) Pattern

    The MVC pattern is a widely adopted architectural pattern in web development for structuring applications into three interconnected components: Model, View, and Controller. The Model represents the application’s data and business logic, the View presents the data to the user, and the Controller manages user input and orchestrates interactions between the Model and View.

    Active Record Pattern

    The Active Record Pattern is an architectural pattern that links database records to objects in an object-oriented manner. It encapsulates database operations within the object itself, enabling developers to interact with the database using object-oriented methods rather than raw SQL queries. By integrating the Active Record Pattern, developers can streamline CRUD operations (Create, Read, Update, Delete) on database records, simplifying data manipulation and retrieval tasks.

    By following the Active Record Pattern, each object instance corresponds to a row in the database table, allowing developers to manipulate data directly through the object’s methods, enhancing code readability and maintainability.

  • Database

    Database Basics

    MySQL Commands

    MySQL is a widely-used open-source relational database management system. Here are some essential MySQL commands for database management:

    • Establishing a connection:
    • $link = mysql_connect("host", "username", "password");
      $db = mysql_select_db("database", $link);
    • Executing queries:
    • $rs = mysql_query("query", $link); // Retrieve data
      $rs = mysql_query("query", $link); // Execute commands
    • Fetching data:
    • $row = mysql_fetch_array($rs); // Retrieve data as an index array
      $row = mysql_fetch_assoc($rs); // Retrieve data as an associative array
    • Managing connections:
    • mysql_close($link); // Close connection
    • Additional functions:
    • mysql_insert_id($rs); // Get ID of the last inserted record
      mysql_error($link); // Retrieve the last error
      $output = mysql_real_escape_string("unescaped_string", $link); // Secure data

    Creating New Links with MySQL

    To create a new link with additional security in MySQL, set the newlink parameter to true:

    $link = mysql_connect("host", "username", "password", true);

    MySQLi (MySQL Improved)

    MySQLi is an enhanced extension of MySQL in PHP, providing improved features and security. Key features of MySQLi and PHP Data Objects (PDO) include:

    • Connection versatility
    • Enhanced security through prepared statements
    • Support for atomic transactions with beginTransaction, commit, and rollBack
    try {
        $dsn = 'mysql:host=localhost;dbname=library';
        $dbh = new PDO($dsn, 'dbuser', 'dbpass');
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $dbh->beginTransaction();
        $affected = $dbh->exec("sql"); // Execute SQL query
        $dbh->commit(); // Commit transaction
        $dbh->rollBack(); // Roll back transaction
    
        $sql = "SELECT * FROM table WHERE id = :param1";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':param1', $param1);
        $stmt->execute();
        $results = $stmt->fetchAll();
    
        foreach ($results as $row) {
            // Process each row
        }
    } catch (PDOException $e) {
        echo "Failed: " . $e->getMessage();
    }

    Persistent Connections

    Persistent connections in databases maintain their state even after executing a script. Various ways to establish persistent connections based on the database extension used include:

    • In MySQL:
    • mysql_pconnect();
    • In MySQLi:
    • mysqli_connect("p:host", "username", "password");
    • Using PDO:
    • $dsn = 'mysql:host=localhost;dbname=example_db';
      $options = array(PDO::ATTR_PERSISTENT => true);
      $dbh = new PDO($dsn, 'dbuser', 'dbpass', $options);
  • Arrays

    Arrays in PHP

    Array Construction

    Arrays in PHP can be constructed using different methods:

    • array() construct: This is a language construct to create an array in PHP.
    • Array operator []: Using square brackets to define and initialize an array.

    Array Printing

    Printing arrays in PHP can be done using various functions:

    • print_r(): This function is used to display human-readable information about a variable, especially useful for arrays.
    • var_dump(): A debugging function that displays structured information about variables, including type and value.
    • var_export(): Outputs or returns a parsable string representation of a variable, mainly used for debugging arrays.

    Array Operations

    Performing operations on arrays in PHP involves various functions and methods:

    • array(key = value) and array[key]=value: Ways to define key-value pairs in an array in PHP.
    • Merging arrays: Using the + operator to merge two arrays into a new array.
    • extract($arr, EXTR_PREFIX_ALL): Imports variables into the current symbol table from an array.
    • count($arr, 1): Counts the number of elements in an array recursively, with the second argument to count elements in sub-arrays.

    Array Cursors

    PHP provides array cursor functions for easy navigation and manipulation:

    • reset(): Resets the internal array pointer to the first element of the array.
    • end(): Moves the internal array pointer to the last element of the array.
    • next(): Advances the array pointer to the next element and returns its value.
    • prev(): Moves the array pointer to the previous element and returns its value.