note 98691 added to language.oop5.magic

From: Date: Thu, 01 Jul 2010 04:29:07 +0000
Subject: note 98691 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-170612@lists.php.net to get a copy of this message
C++-style operator overloading finally makes an appearance with the introduction to __invoke(). Unfortunately, with just '()'. In that sense, it is no more useful than having a default class method (probably quite useful actually) and not having to type out an entire method name. Complimenting wbcarts at juno dot com's point class below, the following allows calculating distance between one or more graph points... <?php class point { public $x; public $y; function __construct($x=0, $y=0) { $this->x = (int) $x; $this->y = (int) $y; } function __invoke() { $args = func_get_args(); $total_distance = 0; $current_loc = $this; foreach ($args as $arg) { if (is_object($arg) and (get_class($arg) === get_class($this))) { $total_distance += sqrt(pow($arg->x - $current_loc->x, 2) + pow((int) $arg->y - $current_loc->y, 2)); $current_loc = $arg; } else { trigger_error("Arguments must be objects of this class."); return; } } return $total_distance; } } $p1 = new point(1,1); $p2 = new point(23,-6); $p3 = new point(15,20); echo $p1($p2,$p3,$p1); // round trip 73.89 ?> Functionally, __invoke() can also be used to mimic the use of variable functions. Sadly, attempting any calling of __invoke() on a static level will produce a fatal error. ---- Server IP: 208.69.120.55 Probable Submitter: 70.124.94.109 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php Edit -- https://master.php.net/note/edit/98691 Del: integrated -- https://master.php.net/note/delete/98691/integrated Del: useless -- https://master.php.net/note/delete/98691/useless Del: bad code -- https://master.php.net/note/delete/98691/bad+code Del: spam -- https://master.php.net/note/delete/98691/spam Del: non-english -- https://master.php.net/note/delete/98691/non-english Del: in docs -- https://master.php.net/note/delete/98691/in+docs Del: other reasons-- https://master.php.net/note/delete/98691 Reject -- https://master.php.net/note/reject/98691 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#170612) next »