Hi,
I'm new to this site so please be gentle! :-) I am seeing more and more PHP apps incorporating the syntax 'variable->do_something()->do_something_else()' using OOP... But I'm struggling to understand what this actually does.
I am fairly new to OOP with PHP, but I know how to instantiate a class, '$variable = new [Class]', and call a class function using, '$variable->setDb()', for example, but I'm struggling to understand the nested function aspect.
Can anyone shed some light on the purpose of such a syntax, what it might be used for (some examples may be useful also)?
Thanks in advance...
Nested functions within class
Started by lordbressers, Aug 18 2010 04:23 PM
1 reply to this topic
#1
Posted 18 August 2010 - 04:23 PM
#2
Posted 20 August 2010 - 12:41 PM
Hi lordbressers,
Welcome to PHPTalk.com, and apologies for the late response.
When you see calls such as $obj->something->doStuff() - it's a principle called object composition, where you initiate other classes within a class - and store their object in properties of that class. This allows you to use relatively simple classes (serving different purposes) to construct a more complex/powerful class - think of it as a form of inheritance. A typical use case for this is a forum such as this one - where you have a base controller class, and various sub-functionality (e.g. posting, registering members, messaging, etc) divided into their respective classes.
A simple example:
This will allow any method within my instance of MyApp to utilize a single instance of the database class, as well as allow anyting implementing MyApp to access these for their own purposes.
A practical aspect of this is that if someone wanted to override a login method of my application (e.g. doLogin from the example) - they could simply extend my login class and write their own implementation without ever having to touch my code. You can also achieve multiple inheritance (reuse code from several sources), which is not possible using traditional inheritance in PHP.
--
When it comes to calls along the lines of $obj->doSomething()->doStuff() - this is a technique called method chaining. PHP 5 methods have the ability to return objects. We can use this to group calls together and create a chain.
An example.. Let's say we have a class for building a car.
Which will print "You have constructed a red car with a 250 BHP engine. What a beast!"
How exactly does it work? Well, the first method we call in the chain (setEngine) assigns the amount of horsepower to the Car's engine property. It then returns $this - which is the object representing our car. At this point our car has a 250 BHP engine, but no color/paint. Next up in our chain is setPaintColor() - and what PHP does next is to execute setPaintColor() belonging to what the previous method returned. Since we returned our car object, we will still have it's properties and can continue building/working on it. When setPaintColor('red') is invoked, it's on the same car object as we previously set the engine for. When we in the end call listSpec() - this method is invoked on the same object, and is thus able to access the properties set by the previous method calls to list the result of our build process.
One of the reasons to why people like using this technique is that it allows you to reduce repeated code, and keep things clean. The alternative to the above snippet would be this:

- S.
Welcome to PHPTalk.com, and apologies for the late response.
When you see calls such as $obj->something->doStuff() - it's a principle called object composition, where you initiate other classes within a class - and store their object in properties of that class. This allows you to use relatively simple classes (serving different purposes) to construct a more complex/powerful class - think of it as a form of inheritance. A typical use case for this is a forum such as this one - where you have a base controller class, and various sub-functionality (e.g. posting, registering members, messaging, etc) divided into their respective classes.
A simple example:
<?php
class MyApp {
public function __construct(){
require_once('libs/class.db.mysql.inc.php');
requite_once('libs/class.login.inc.php');
$this->db = new MyDBHandler();
$this->login = new MyLoginHandler();
}
(...)
public function doShizzle(){
return $this->db->query('SELECT * FROM some_table');
}
}
$app = new MyApp();
// Returns a query result
$app->doShizzle();
// Do a custom DB Query against the same database
$app->db->query("SELECT foo FROM bar WHERE foo = 'abcd'");
// Initiate login procedure
$app->login->doLogin();
?>
This will allow any method within my instance of MyApp to utilize a single instance of the database class, as well as allow anyting implementing MyApp to access these for their own purposes.
A practical aspect of this is that if someone wanted to override a login method of my application (e.g. doLogin from the example) - they could simply extend my login class and write their own implementation without ever having to touch my code. You can also achieve multiple inheritance (reuse code from several sources), which is not possible using traditional inheritance in PHP.
--
When it comes to calls along the lines of $obj->doSomething()->doStuff() - this is a technique called method chaining. PHP 5 methods have the ability to return objects. We can use this to group calls together and create a chain.
An example.. Let's say we have a class for building a car.
<?php
class Car {
private $engine;
private $color;
public function setEngine($bhp){
$this->engine = $bhp;
return $this; // Return the car object
}
public function setPaintColor($color){
$this->color = $color;
return $this;
}
public function listSpec(){
printf('You have constructed a %s car with a %d BHP engine. What a beast!', $this->color, $this->engine);
}
}
?>
We can now simply call this to construct a car and list it's spec:<?php
$myCar = new Car();
$myCar->setEngine(250)->setPaintColor('red')->listSpec();
?>
(This can be done in an arbitrary order - as long as listSpec() is last.)Which will print "You have constructed a red car with a 250 BHP engine. What a beast!"
How exactly does it work? Well, the first method we call in the chain (setEngine) assigns the amount of horsepower to the Car's engine property. It then returns $this - which is the object representing our car. At this point our car has a 250 BHP engine, but no color/paint. Next up in our chain is setPaintColor() - and what PHP does next is to execute setPaintColor() belonging to what the previous method returned. Since we returned our car object, we will still have it's properties and can continue building/working on it. When setPaintColor('red') is invoked, it's on the same car object as we previously set the engine for. When we in the end call listSpec() - this method is invoked on the same object, and is thus able to access the properties set by the previous method calls to list the result of our build process.
One of the reasons to why people like using this technique is that it allows you to reduce repeated code, and keep things clean. The alternative to the above snippet would be this:
<?php
$myCar = new Car();
$myCar->setEngine(250);
$myCar->setPaintColor('red');
$myCar->listSpec();
?>
Hope that gives you an idea. - S.
Hi there! If you found this post useful, or used this information to help others, we would greatly appreciate a link back to our forum from your website/blog. Thanks! =)
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users












