PHP

Type Hinting

As I have seen repeatedly throughout this tutorial, PHP takes a dynamic approach to typing and doesn't require us to declare types when I want to use variables or add parameters to functions. However, one place where PHP does give us some extra control of typing is in passing parameters to functions. Programmers now have the option of providing a type hint this is a way to tell PHP that I expect a parameter to be of a certain class. However, I cannot do this with things that are not objects (for example, integers or strings).

<?php
  function get_product_info(IProduct $in_product)
  {
  // etc.
  }
?>

In the previous code snippet, the function expects its sole parameter to be of type IProduct. This means that any class that implements IProduct, such as my LocalProduct, NavigationPartnerProduct, or SuperBoatsProduct classes, is acceptable as a parameter to this function. If I wanted the function to only accept function classes that I have written in-house and inherit from Product, I could declare it as follows:

<?php
  function get_product_info(Product $in_product)
  {
    // etc.
  }
?>

If you try to pass a parameter that does not match the type hint, PHP gives you an error.

Fatal error: Argument 1 must be an object of class IProduct in
  c:\Inetpub\wwwroot\phpwebapps\src\hints on line 7


Autoloading

An additional feature in PHP provides for automatic loading of include files which I'll make quick mention of here in case you run across code that use it.

Since most of my class definitions will be in separate files that I can reuse and share between web application scripts, I are obliged to require or include those files in any script that uses those classes.

PHP5 provides the ability to skip these inclusions, if you so desire, by letting you implement a special function in your script called __autoload. This function receives the name of a class for which PHP cannot find a definition as a parameter. Therefore, you can determine which file you wish to include inside of this function, and then issue the appropriate require or include (or require_once or include_once) operation.

<?php
  //
  // all my classes are in files with the pattern:
  // "classname".inc
  //
  function __autoload($in_className)
  {
    require_once("$in_className.inc");
  }
?>

Again, I'll not use this functionality in the tutorial since I'll always strive to be explicit and deliberate in my coding. Also, this functionality will not work if my autoloaded class inherits from a base class that is in a separate file that has not been loaded.

by BrainBellupdated
Advertisement: