|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-11-24 14:50 UTC] ninzya at inbox dot lv
Description:
------------
I'd like to propose an extension to PHP syntax, that would allow programmer to
avoid code duplication in some cases and, therefore, would make PHP code more
readable.
My idea is to extend dynamic call operator ("->method()") add a "context" syntax
to it's arguments. The syntax would mean that the argument's value is located in
context of a specific object - the argument is either a property or method. The
syntax could be as follows:
$obj->area( :$x, :$y);
Note the ":" (colon) character in front of argument. The colon means that the
argument for the call is a property of object that the invoked method belongs
to. In this case both arguments are actually "$obj->x" and "$obj->y" values.
Syntax for method calls is as follows:
$obj->area( :x(), :y());
In this case both arguments are "$obj->x()" and "$obj->x()".
The following more complex example:
$obj->area( :mt_rand( 1, :$x), $y);
Here mt_rand() is a method of $obj (i.e. "$obj->mt_rand()", because colon
character is preceding the function name)) and since ":mt_rand()" is resolved to
"$obj->mt_rand()", it's ":$x" argument is resolved to "$obj->x" as well.
However, a call like this:
mt_rand( :$x);
should yield a runtime error because this is not a dynamic call and the argument
can not be resolved.
Test script:
---------------
class Test {
public $x =5;
public function y() {
return 10;
}
public function area( $x, $y, $name) {
echo $name .': ' .$x .' x ' .$y;
}
public function makeName( $name) {
return '#' .$name;
}
}
$test =new Test;
$test->area( :$x, :y(), :makeName( 'test'));
Expected result:
----------------
#test: 5 x 10
Actual result:
--------------
Not implemented yet.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Dec 08 01:00:02 2025 UTC |
An example on how the proposed syntactic sugar would improve code readability. Before: if( $user->hasPermission( $user::PERM_EDIT, $user->getProfile())) { // has access to edit own profile } After: if( $user->hasPermission( :PERM_EDIT, :getProfile())) { // has access to edit own profile } Before: $config->setSettings([ $config::SOME_TTL =>10, $config::SOME_PATH =>"/var/www/...", $config::SOMETHING_OTHER =>0xFF ]); After: $config->setSettings([ :SOME_TTL =>10, :SOME_PATH =>"/var/www/...", :SOMETHING_OTHER =>0xFF ]); Note that use of ":" inside array definition contextually resolves arguments as well. In the last example the ":SOME_TTL" syntax refers to the "SOME_TTL" class constant of $config object (i.e. same as "$config::SOME_TTL")