PHP notes for Java programmer (4) - classes

Here is the last set of PHP notes which cover object oriented programming in PHP. The notes conclude with a set of supplementary notes. The entire list of PHP notes are available here.

PHP Notes - Object oriented programming

1. To call class methods without an instance, use scope resolution operator(::) else use (->). Check the following example,

class test {
 function f1() {
  echo “hello”;
 }
}

test::f1();

$t1 = new test();
$t1->f1();

2. In PHP, __autoload function (automatically called) can be used to simulate “import” functionality. This is very handy if you store your classes in separate PHP files. For example,

<?php
function __autoload($class_name) {
    require_once $class_name . ‘.php’;
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

3. PHP has constructors (__construct()) and destructors (__destruct()). There is no chaining of constructor or destructor calls. Use parent::__construct() for the same.

4. Method and properties can have “public”, “private” or “protected” visibility.

5. Use const keyword to define constants inside classes.

6. PHP has the standard class constructs - abstract, extends, interface, implements etc.

7. It is possible to overload method calls and member access using __call, __get and __set. This will be triggered only if the accessed attribute or method doesn’t exist! isset() and unset() can also be overridden using __isset() and __unset().

8. For serialization methods __sleep and __wakeup. All methods starting with __ are reserved as magic methods in PHP!

9. To perform shallow copy, use clone directive. It is also possible to define a __clone() method.

10. PHP supports reflection paradigm. For more details, checkout http://www.php.net/manual/en/language.oop5.reflection.php

11. PHP supports type hinting for object and array types. For example, function f1(array $a) { }

12. A typical PHP class declaration is shown below,

class Test extends T1 implements T2 {

 public $a;
 
 public function testmethod($value) {
  $this->a = $value;
 }
}

13. PHP exception handling is similar to Java. It is also possible to extend the base “Exception” class. Here is a sample use of exception,

try {
    $error = ‘error message’;
    throw new Exception($error);
} catch (Exception $e) {
    echo ‘Caught exception: ‘,  $e->getMessage(), “\n”;
}

PHP supplementary notes

1. For maximum security always validate user input. You don’t want to be a victim of SQL injection attack!

2. For database access, provide least access rights needed by the application.

3. On a production system it is better to disable error reporting.

Leave a Reply