Showing posts with label interface. Show all posts
Showing posts with label interface. Show all posts

Friday, June 5, 2009

Object iteration 1/2

the construct foreach in PHP5 supports also object, in addition to arrays.

foreach($object as $key=>$val)
{
//$key will be equal to the nth member name
//$val will be equal to the nth member value
}

Which members are visibile ? it depends on the "foreach" position !
  • inside the class ($this is the object): all the members are visibile
  • outside the class: only public members are visible
  • inside an inherited class: public and protected
Example:

class A
{
public $a;
public
$b;
private
$p;
public function
__construct($a, $b, $p){
$this->a = $a;$this->b = $b; $this->p = $p;
}
public function
f()
{

foreach(
$this as $k=>$v)

{print "$k => $v \n"; }
}
}

$a = new A(1,2,3);

foreach(
$a as $k=>$v)
{
print "$k => $v \n";
} //a => 1 b => 2

$a->f(); //a => 1 b => 2 p => 3

Thursday, June 4, 2009

php5 interfaces

PHP5 supports "interfaces".
What is an interface ? Basically, it's a definition of a class type with methods. If you implement an interface, you must write all the methods in that interface.

Example:
Let's suppose there is a "dbConnection" interface, that contains all the methods to db access.

Interface dbConnection
{
public function __construct($host, $user, $pass, $db);
public function query($q);
public function getError();
public function getAffectedRows();
public function nextRow();
/
/[...]
}


Now you can already write an application that use the methods of the interface, regardless of the implementation of the methods.

//application
$db = new MySQL("localhost","user" [...]);
$db->query("select * from table");
while (
$row = $db->nextRow())
print
"{$row->field1} {$row->field2}"

Let's write the class for MySQL access

class MySQL implements dbConnection
{
private $conn;
public function
__construct($host, $user, $pass, $db)
{
$this->conn = mysql_connect($host, $user, $pass);
mysql_select_db($db, $this->conn);
}
//[..
other methods...]
}


And a class for SQLite

class SQLite implements dbConnection
{
private $conn;
public function
__construct($host, $user, $pass, $db)
{
$this->conn = sqlite_open($db);
}
//[.. other methods]
}


Now if want to change the application and use SQLite instead of MySQL, you have to modify ONLY the 1st line:

$db = new SQLite("","","","/path/to/file.db");

You don't need to check the rest of the code. MySQL and SQLite classes implements the same interface (and the same methods) !
Interfaces improve your code !

 

PHP and tips|PHP