<?php
$name = 'Ray';
$phone = '703.555.1212';
$email = 'ray@gmail.com';
<?php
$name1 = 'Ray';
$phone1 = '703.555.1212';
$email1 = 'ray@gmail.com';
$name2 = 'Toby';
$phone2 = '703.555.1212';
$email2 = 'toby@gmail.com';
$name3 = 'Lucky';
// NOTICE THAT THERE IS NO PHONE #3
$email3 = 'lucky@gmail.com';
<?php
$names = [ 'Ray', 'Toby', 'Lucky' ];
$phones = [ '703.555.1212', '703.555.1212' ];
$emails = [ 'ray@gmail.com', 'toby@gmail.com', 'lucky@gmail.com' ];
<?php
Class Person
{
public $name, $phone, $email;
}
<?php
$person = new Person;
$name = 'Ray';
$phone = '703.555.1212';
$email = 'ray@gmail.com';
$person->setName($name);
$person->setPhone($phone);
$person->setEmail($email);
$per_id = $person->save();
<?php
$person = new Person;
$person->name('Ray')->phone('703.555.1212')->email('ray@gmail.com')->save();
<?php // demo/magic_call.php
error_reporting(E_ALL);
Class Person
{
/**
* The constructor for the class - assigns the properties from the data model
* @param none
* @return none
*/
public function __Construct()
{
// STUB FUNCTION: SIMULATE GETTING THE STRUCTURE OF THE DATA MODEL
$this->name = $this->phone = $this->email = NULL;
}
/**
* Save the data model by inserting or replacing its row in the database
*
* @param none
* @return id The id of the row in the database
*/
public function save()
{
// STUB FUNCTION: SIMULATE SAVING THE MODEL
return 1;
}
/**
* Magic Setter for any Object Property
*
* @see http://php.net/manual/en/language.oop5.overloading.php
* @param $argname The property to be set (must exist)
* @return $this The existing object returns itself
* @error E_USER_ERROR if the named property does not exist
*/
public function __call($argname, array $arglist)
{
if ( ! property_exists($this, $argname) )
trigger_error("Property <b><i>$argname</i></b> is undefined on the " . __CLASS__ . " data model", E_USER_ERROR);
$this->$argname = $arglist[0];
return $this;
}
}
// DEMONSTRATE
$p = new Person;
$id = $p->name('Ray')->phone('703')->email('EE')->save();
// SHOW THE DATA STRUCTURES
var_dump($id, $p);
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (1)
Commented:
Open in new window
While this retains the interface, the error-handling path gets disconnected from the flow. Also note that once you've thrown an error, there's no way of getting back into the call chain to fix the problem and continue - you have to start again.
There is a ton of debate on exceptions vs return values, but broad exceptions are great way of handling large-scale problems, for example your database connection breaking when you're busy thinking about something else.