Making PHP code shorter
I have found that writing PHP code within classes can become rather long:
$this->parser->parse_syntax($this->get_language_path($this->language),
$this->elements,
开发者_Go百科 $this->regex);
For example, in Java a class instance can call its methods by name without referencing this, is there a way to achieve shorter code in PHP without using this and self every time you have to read a value?
No, in PHP if you want to run object's method or read/write property from inside of object you must write $this
to refer that object instance.
PS. You can do at the beginning of each method something like this: $s = $this
and use $s
then, but it's strongly unrecommended, you shouldn't do that and it will be best, if you forget that you read this paragraph :)
I think it all comes down to your data structure, for instance your parse_syntax()
method can default to $this->elements
and $this->regex
if null is passed instead:
class foo
{
public $parser = null;
public $language = null;
public $elements = null;
public $regex = null;
public function __construct()
{
$this->parser = new parser();
}
public function get_language_path($language = null)
{
$language = (isset($language)) ? $language : $this->language;
// your code here
}
}
class parser extends foo
{
public function parse_syntax($path = null, $elements = null, $regex = null)
{
$path = (isset($path)) ? $path : parent::get_language_path();
$elements = (isset($elements)) ? $elements : $this->elements;
$regex = (isset($regex)) ? $regex : $this->regex;
// your code here
}
}
Yes, Java does not always need this, it also does not need the $ in front of variables, and you use just one dot (.) instead of -> to reference object's variable.
But Python is still shorter than Java - you don't need to use braces in Python, then use Python. Scala also much shorter than Java, so if you really need to write less code, then php is not the best choice.
Look into Python or Scala
精彩评论