More about $this on php -
*update example
have read articles , php.net . still having problem understand $this on 'this' example. understand basic used .
let's assume , have function @ end homecoming $this; //nothing come after $this
what $this (at end of method to) refer ? how check/echo-ing $this is
public function check($source, $items = array()){ foreach ($items $item => $rules) { foreach($rules $rule => $rule_value){ $value = trim($source[$item]); $item = escape($item); if($rule === 'required' && empty($value)) { $this->adderror("{$item} required"); } else if(!empty($value)) { switch($rule) { case 'min': if(strlen($value) < $rule_value ) { $this->adderror("{$item} must minimum of {$rule_value} characters"); } break; case 'max': if(strlen($value) > $rule_value ) { $this->adderror("{$item} must maximum of {$rule_value} characters"); } break; } } } } if(empty($this->_errors)) { $this->_passed= true; } homecoming $this; }
*this code part of register , validation class. point still $this @ end refering . thanks
in example, $this
refers main class , object.
class mainclass { public function dosomething($x, $y) { $this->content = "rssult is: " . $x+$y; homecoming $this; } public function printme() { echo $this->content; }
}
it returns object , class.
now usage? 1 of fundamental usages method-chaining. well, mean?
have ever seen this?
$myclass = new mainclass(); $myclass->dosomething()->print();
the above code implemented approach called method-chaining, since there chain of methods (functions) called repeatedly without stop.
basically, without method-chaining, above code have been:
$myclass = new mainclass(); $s = $myclass->dosomething(5, 8); $myclass->print();
but method chaining, since each method returns whole class if have had new mainclass() , allows immediate phone call method.
though not new mainclass()
since "new
" operator creates instance of class, while $this
returns current instanced.
in nutshell, $this says php please homecoming current instanced re-create of class (whose properties might have been changed methods called prior returning $this).
php
No comments:
Post a Comment