PHP Classes

PHP Classes
A class is a collection of variables and functions (methods) that are directly associated with each other.
The manner in which PHP defines and uses a class is different between PHP Version 4 and Version 5. We will concentrate on Version 4's implementation since that is what our student server is running.
A class is defined using the following syntax:
class classname {

  var $associated_class_variables;

  class_function_definitions
}
Within the associated class functions, class variables and class function references must be preceded by a $this-> pointer dereference in order to distinguish between locally-defined data inside the function and other externally-defined functions.
class Cart {
  var $items;  // Items in our shopping cart

  // Add $num articles to the cart
  function add_item ($article, $num) {
    $this->items[$article] += $num;
    } add_item

  // Take $num articles of out of the cart
  function remove_item ($article, $num) {
    if ($this->items[$article] > $num) {
      $this->items[$article] -= $num;
      return true;
      }
    else return false;
    } // remove_item

  // Add multiple articles using array
  function add_items ($articles) {
    foreach ($articles as $article=>$num)
      $this->add_item ($article,$num);
    } // add_items

} // end class Cart

PHP Version 4 Class Cautions
You can NOT break up a class definition into multiple files, or multiple PHP blocks. The following will not work:
<?php
class test {
?>
<?php
  function test() {
    print 'OK';
  }
}
?>
Only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function (a constructor) which is called automatically when an object is being constructed from the class. The constructor function has the same name as the class itself.
class Cart {

  // None of these will work in PHP 4
  var $todays_date = date('Y-m-d');
  var $name = $firstname;
  var $owner = 'Fred ' . 'Jones';

  // Constant values will work, including arrays
  //    containing constants
  var $init_value = 5;
  var $items = array('VCR', 'TV');
}

// Correct way for PHP Version 4
class Cart {
  var $todays_date, $name, $owner,
      $init_value=5;
  var $items = array('VCR', 'TV');

  function Cart() { // constructor
    global $firstname;
    $this->todays_date = date('Y-m-d');
    $this->name = $firstname; // $GLOBALS['firstname'];
    // etc. . .
  } // Cart constructor
} // class Cart

Using PHP Classes
Classes are types. They are blueprints for actual variables. You have to create a variable of the desired type with the new operator.
$cart = new Cart;
$cart->add_item('10', 1);

$another_cart = new Cart;
$another_cart->add_item('0815', 3);

Extending PHP 4 Classes
You often need classes with similar variables and functions to another existing class. In general, it is good practice to define a generic class that can be used in all your projects and adapt this class for the needs of each of your specific projects. Classes can therefore be extensions of other classes.
The extended or derived class has all variables and functions of the base class (called inheritance) and what you add in the extended definition.
It is not possible to subtract from a class; that is, to undefine any existing functions or variables.
An extended class is always dependent on a single base class; that is, multiple inheritance is not supported.
Classes are extended using the keyword extends.
class Named_Cart extends Cart {
  var $owner;

  function set_owner ($nameIn) {
    $this->owner = $nameIn;
  }
}
This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the cart's owner. You can still use normal cart functions on named carts:
$ncart = new Named_Cart;    // Create a named cart
$ncart->set_owner('kris');  // Name that cart
echo $ncart->owner;         // print the cart owners name
$ncart->add_item('10', 1);  // (inherited functionality from cart)
It is possible to override a method innherited from a parent class by simply redefining the method:
class A {
  var $foo;

  function A() { $this->foo = 'test'; }
  function bar() { echo $this->foo . ' : Running in A'; }
}

class B extends A {
  function bar() { echo $this->foo . ' : Running in B'; }
}

$myClass = new B;
$myClass->bar(); // will output "test: Running in B'

Scope Resolution Operator (::)
Sometimes it is useful to refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this.
class A {
  function example() {
    echo "I am the original function A::example()";
  }
}

class B extends A {
  function example() {
    echo "I am the redefined function B::example()";
    A::example();
  }
}

// there is no object of class A.
// this will print:
//  I am the original function A::example()
A::example();

// create an object of class B.
$b = new B;

// this will print:
//  I am the redefined function B::example()
//  I am the original function A::example()
$b->example();
There are class functions, but there are no class variables. In fact, there is no object at all at the time of the call. Thus, a class function may not use any object variables (but it can use local and global variables), and it may no use $this at all.

parent Special Name
You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialization of code in your base class.
Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should the inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class.
class A {
  function example() {
    echo "I am A::example() and provide basic functionality";
  }
}

class B extends A {
  function example() {
    echo "I am B::example() and provide additional functionality";
    parent::example();
  }
}

$b = new B;

// This will call B::example(), which will in turn
//    call A::example().
$b->example();

Class Method (Function) Overloading in PHP
Unlike C++, PHP 4 does not allow you to overload a method in a class:
class Test {
  var $data;
  
  function process() { ... }
  function process($test) { ... } // ERROR!
}
You can, however, use PHP's ability to pass a varying number of function parameters, coupled with its detailed variable typing functions, to simulate the same effect as function overloading.
The following functions can be useful in this respect:
func_num_args() returns the number of arguments passed to this function during the current call
func_get_arg(int) returns the value of the specified argument position from the argument list passed to this function during the current call
func_get_args() returns an array of the arguments passed to this function during the current call
function test () {
  $args = func_get_args();
  foreach ($args as $arg) {
    if (is_integer($arg)) { ... }
    elseif (is_string($arg)) { ... }
    elseif (is_real($arg)) { ... }
    elseif (is_bool($arg)) { ... }
    else { ... }
    }
} // test

test (12,56.2,'data',true);
test (100.123,false);
Another common approach to handle a varying number of arguments to a function is to pass all the arguments as elements in a single array, so rather than passing an unknown number of arguments, a single array argument is passed instead. A function like this can also be easily manipulated to work with a scalar parameter equally as well.
function test ($args) {
  if (!is_array($args)) $args = array($args);
  foreach ($args as $arg) {
    if (is_integer($arg)) { ... }
    elseif (is_string($arg)) { ... }
    elseif (is_real($arg)) { ... }
    elseif (is_bool($arg)) { ... }
    else { ... }
    }
} // test

test (array(12,56.2,'data',true));
test (array(100.123,false));
test ('scalar');

PHP 5 Classes
New __construct and __destruct methods
PHP 5 introduces specific functions to be used as a constructor and destructor for a class.
class MyDestructableClass {
   function __construct() {
     echo "In constructor\n";
     $this->name = "MyDestructableClass";
   }

   function __destruct() {
     echo "Destroying {$this->name}\n";
   }
} // class MyDestructableClass

$obj = new MyDestructableClass();
Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used, such as the initialization of non-constant member (instance) variables.
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed.
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

PHP 5 Class Visibility
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.
Member Visibility
// Define MyClass
class MyClass {
  public    $public = 'Public';
  protected $protected = 'Protected';
  private   $private = 'Private';

  function printHello() {
   echo $this->public;
   echo $this->protected;
   echo $this->private;
   }
} // MyClass

$obj = new MyClass();
echo $obj->public;    // Works!
echo $obj->protected; // Fatal Error
echo $obj->private;   // Fatal Error
$obj->printHello();   // Shows Public, Protected and Private


// Define MyClass2
class MyClass2 extends MyClass {
  // We can redeclare the public and protected method,
  //   but not private
  protected $protected = 'Protected2';

  function printHello() {
    echo $this->public;
    echo $this->protected;
    echo $this->private;
    }
} // MyClass2

$obj2 = new MyClass2();
echo $obj->public;     // Works!
echo $obj2->private;   // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello();   // Shows Public, Protected2, not Private
The PHP 4 method of declaring a variable with the var keyword is no longer valid for PHP 5 objects. For compatibility a variable declared in php will be assumed with public visibility, and a E_STRICT warning will be issued.
Share on Google Plus

About M

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment