OOP and exception handling in PHP: classes and objects; constructors and property visibility; inheritance and method overriding; exception handling (try, catch, finally, throw); input validation using regular expressions

PHP is fully object-oriented: classes with __construct and public/private/protected visibility, inheritance with extends, try/catch/finally for errors, and preg_match for regex validation.

12 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The portal outgrows loose functions

The event portal now has scattered variables and functions: an event's name here, its seats there, a validation function somewhere else. You have felt this smell before, in BCA403 (Java) and BCA404 (VB.NET): related data and behaviour belong TOGETHER, in a class.

PHP is fully object-oriented, and the good news is that the CONCEPTS are exactly the ones you already know: classes, constructors, visibility, inheritance, exceptions. Only the SYNTAX is new ($this->, __construct, extends). This lesson gives the portal proper structure and robust error handling.

Theory

Classes, the PHP way

A class groups properties and methods:

  • the constructor is the special method `__construct()` (2 underscores), run automatically at new
  • inside methods, refer to the object's own members with `$this->property` (the ARROW ->, not a dot)
  • visibility: private (this class only), protected (class + subclasses), public (everywhere): the same 3 levels as Java
  • inheritance: class VipEvent extends Event { }, with method OVERRIDING and parent::method() to call the parent version

Instantiate with new: $e = new Event("Garba Night", 350);. If this feels like BCA403 with different punctuation, that is exactly right.

Practical

An Event class with a validating constructor

<?php
  class Event {
    private $name;
    private $seats;

    public function __construct($name, $seats) {
      if ($seats < 0) {
        throw new Exception("Seats cannot be negative");
      }
      $this->name = $name;      // $this->  , arrow not dot
      $this->seats = $seats;
    }

    public function describe() {
      return $this->name . ": " . $this->seats . " seats";
    }
  }

  try {
    $e = new Event("Garba Night", 350);
    echo $e->describe();        // Garba Night: 350 seats
    $bad = new Event("Ghost", -5);   // throws
  } catch (Exception $ex) {
    echo "Error: " . $ex->getMessage();   // Error: Seats cannot be negative
  } finally {
    echo "<br>Done";           // always runs
  }
?>

Theory

Exceptions and regex validation

Exception handling is the BCA403 grammar with PHP names:

try { ... } catch (Exception $e) { echo $e->getMessage(); } finally { ... }

throw new Exception("message") raises one; the matching catch handles it; finally ALWAYS runs (cleanup), whether or not an exception occurred. Same flow you traced in Java: the risky code runs, an exception jumps to catch, finally executes regardless.

Regex validation uses preg_match("/pattern/", $string), which returns 1 if the string MATCHES the pattern. It is how you validate FORMATS: a 10-digit phone number, a specific code. Regex plus filter_var (last lessons) cover most input-validation needs.

Quiz

Inside a PHP class method, how do you access the object's own 'name' property?

  1. this.name (dot notation, like Java)
  2. $this->name (the arrow operator)
  3. $name directly
  4. self.name
Show the answer

$this->name (the arrow operator)

PHP uses $this->name: the special variable $this refers to the current object, and the ARROW operator (->) accesses its members. Option A uses Java/JavaScript DOT notation, which PHP does not use for object members (a very common cross-language slip). Option C ($name alone) would be a local variable, not the property. Option D (self.name) is not PHP syntax (self:: exists but for static members, with ::). The 2 PHP-specific things to remember: $this (with the dollar sign) for the current object, and -> (arrow) to reach its properties and methods.

Think first

Translate your Java OOP to PHP

From BCA403 you know: constructor, this.field, extends, try/catch/finally, e.getMessage(). Write each one's PHP spelling. Then tap.

Show the answer

Constructor: __construct() (2 underscores, one special name, not the class name). this.field: $this->field ($this variable, arrow operator). extends: extends (identical to Java). try/catch/finally: try / catch (Exception $e) / finally (same keywords, note the typed catch variable $e). e.getMessage(): $e->getMessage() (arrow again). The concepts: encapsulation via public/private/protected, inheritance, overriding, parent::, exceptions: are IDENTICAL to Java; only the punctuation changed ($, ->, __construct). This is the payoff of learning OOP properly once: your fourth OOP language took one lesson, because you were learning syntax, not concepts.

Watch out

PHP OOP traps

Dot instead of arrow: PHP uses $this->name, never this.name.

Wrong constructor name: it is __construct() (2 underscores), NOT a method named after the class (that is old PHP 4 style).

Forgetting $ on $this: it is a variable: $this.

Uncaught exceptions: an exception with no matching catch is a fatal error; wrap risky code in try.

preg_match return: it returns 1 (match), 0 (no match) or false (error): check for 1, do not assume boolean true.

Theory

Unit 2 complete: a structured, safe portal

The portal now has files, JSON, sessions, email, classes and error handling: it is a real, organised PHP application. But it still stores data in flat files, which does not scale. Unit 3 connects it to a proper database (MySQL) with full CRUD and prepared statements, adds AJAX for a live search, and rebuilds it on the CodeIgniter MVC framework, the professional way to structure a PHP app. From scripts to a framework.

Summary

Key takeaways

  • PHP is fully object-oriented: class { }, properties, methods, instantiate with new.
  • The constructor is __construct() (two underscores); access own members with $this->property (arrow, not dot).
  • Visibility: private (class only), protected (class + subclasses), public (everywhere): same as Java.
  • Inheritance: extends, method overriding, parent::method() for the parent version.
  • Exceptions: try / catch (Exception $e) / finally; throw new Exception('msg'); finally always runs.
  • preg_match('/pattern/', $string) returns 1 on a match: use it to validate formats.
  • Memory hook: __construct, $this->, extends: same OOP as Java, new punctuation.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Advanced PHP and File Management

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

OOP and exception handling in PHP: classes and objects; constructors and property visibility; inheritance and method overriding; exception handling (try, catch, finally, throw); input validation using regular expressions · Web Framework and Services (Major-12) · Gri-Learn