I wouldn't do the second approach as the parameters aren't named.
A well-written essay on describing how a template system should work is coming from Parr, it's often quoted by people writing template systems and/or web-mvc frameworks.
Personally, what I usually prefer is to implement an ArrayObject class with a properties array, and the template would refer to $this->propertyName
, which in fact would be the template object's $this->property['name']
. This could be also achieved simply by using __set
and __get
, so:
class Template {
private $_scriptPath=TEMPLATE_PATH;//comes from config.php
public $properties;
public function setScriptPath($scriptPath){
$this->_scriptPath=$scriptPath;
}
public function __construct(){
$this->properties = array();
}
public function render($filename){
ob_start();
if(file_exists($this->_scriptPath.$filename)){
include($this->_scriptPath.$filename);
} else throw new TemplateNotFoundException();
return ob_get_clean();
}
public function __set($k, $v){
$this->properties[$k] = $v;
}
public function __get($k){
return $this->properties[$k];
}
}
and a template would look like:
<html>
<head>
<title><?=$this->title?></title>
</head>
<body>Hey <?=$this->name?></body>
</html>
and invoking it would look like:
$view = new Template();
$view->title="Hello World app";
$view->properties['name'] = "Jude";
echo $view->render('hello.inc');
As far as I remember, this is how the old Symfony 1.x and the Zend_View template engines look like, and for me it's fine.
This is not a php-only issue, therefore there might be potential duplicate questions. Generally
The first approach (return count(...)) is faster to read and in some cases will produce faster code, because of the time consumed to instantiate the variable $count.
The second approach is kind of easier to debug and maintain. Each operations takes place in a distinct line, which is easier to isolate hence debug, since some IDEs can place a debug breakpoint to the exact line. It is also easier to maintain/extend in case you want for example to log the result or do another operation with this.
I do not believe there is a "better" way, or that it matters so much for a one/two liner. I would use the first one and then refactor it in case it had to be extended.
What many people would agree upon is that something like:
log("$array"); return count($array) * 4 - ($array4==null)?(count($array2)^94):int_val($xyz);
should better be broken into different lines.
Best Answer
There are many scenarios in which one might want to return
$this
from a function, but the most popular one is 'method chaining'.For example, in an SQL abstraction layer, you may have an object that represents a query, and then call a series of methods on it to extend it. Consider the following code:
If each of
$query
's methods returns the modified query object, we can instead write this as:The second version is closer to how you'd write an actual SQL query, and it works without introducing the exta
$query
variable.