Anda di halaman 1dari 9

Advance Techniques in PHP

1. Backtracing
2. Method Chaining

Kumar S
Backtracing:
debug_backtrace()
 function bar() {
print_r(debug_backtrace());
}
bar('apple', 'banana', 'pear');
[0] => Array (
[file] => /example.php
[line] => 12
[function] => foo
[args] => Array ( [0] => apple [1] => banana [2] =>
pear )
)

Kumar S
Backtracing:
debug_backtrace()
 $backtrace =
print_r(debug_backtrace(), true);
This will email or log the backtrace

Kumar S
Backtracing:
debug_print_backtrace()
 If debug_print_backtrace() was called
in the same place in the example
script above in place of
debug_backtrace() it would output
the following:
 #0 bar() called at [-example.php:4]
#1 foo(apple, banana, pear) called at [-
example.php:12]

Kumar S
Capture the info from
debug_print_backtrace
 Using debug_print_backtrace
with output buffering
ob_start();
debug_print_backtrace();
$backtrace = ob_get_clean();

 Using the Exception object


$e = new Exception();
$backtrace = $e->getTraceAsString();

Kumar S
Method Chaining
 A Typical Class
class Person
{
private $m_szName;
private $m_iAge;
public function setName($szName)
{
$this->m_szName = $szName;
}
public function setAge($iAge)
{
$this->m_iAge = $iAge;
}
public function getDetails()
{
printf(
'Hello my name is %s and I am %d years old.',
$this->m_szName,
$this->m_iAge);
}
}
 $p1 = new Person();
$p1->setName(‘Kumar');
$p1->setAge(30);
$p1->getDetails();

Kumar S
Method Chaining
 class Person
{
private $m_szName;
private $m_iAge;
public function setName($szName)
{
$this->m_szName = $szName;
return $this; // We now return $this (the Person)
}
public function setAge($iAge)
{
$this->m_iAge = $iAge;
return $this; // Again, return our Person
}
public function getDetails()
{
printf(
'Hello my name is %s and I am %d years old.',
$this->m_szName,
$this->m_iAge);
}
}

Kumar S
Using Method Chaining
 $p1 = new Person();

$p1->setName(‘Kumar')->setAge(30)->getDetails();

Kumar S
How it works
 First up is $p1->setName(‘Kumar'). This assigns the
person's name to be Kumar and returns $this -- that
is, the $p1 object. So at the moment Kumar has his
name, but no age!

Next up comes ->setAge(30). Because we're chained


with the previous method, PHP interprets the code
and says "execute the setAge method belonging to
whatever was returned from the previous method." In
this case, PHP executes the setAge method belonging
to our Person object, $Kumar.
 Recall how we do use trim functions
$x = ltrim(rtrim(“ Some String “));

Kumar S

Anda mungkin juga menyukai