|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2003-09-07 08:29 UTC] andrey@php.net
[2003-09-07 11:04 UTC] sniper@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Nov 06 03:00:01 2025 UTC |
Description: ------------ As noted in a comment to the PHP object/classes page: >It seems there is no way to access the return value of a >method (or any function) inline, without assigning it to a >variable. > >For example: >.... >$test = new Test; > >// This does not work: >$foo = $test->blah()[0]; > >// Instead have to do: >$temp = $test->blah(); >$foo = $temp[0]; > >// Similarly for objects, cannot do: >$foo = $test->childTest()->blah(); > >// Instead have to do: >$temp = $test->childTest(); >$foo = $temp->blah(); > > >:-( I would like to strongly request that PHP add this functionality to a future version. The editor's note says that "PHP is not a hard-core OOP language" --- however, it seems to me that this is a very essential feature if you want to use even fairly basic object-oriented principles. For example, because of this, it is very difficult to use access methods instead of directly accessing instance variables of a class. I.e., suppose I have a class which has an array inside it, called $contents, which contain a variable called $foo. I can do this: $object->contents[5]->foo Suppose I want to use an access method instead: $object->getContents(5) so that I can hide the fact that $contents is an array --- maybe later I might want to change it so it looks up the value in a mysql database or something. I would want to be able to write: $object->getContents(5)->foo (or even better, $object->getContents(5)->foo() ) but I can't. Instead, I have to write the much more cumbersome: $temp = $object->getContents(5); $temp->foo(); Not allowing transparent use of access methods destroys a lot of the power of using object-oriented programming. If you can't use access methods cleanly, then you are forced to reach inside the object and directly access instance variables, violating encapsulation and making it difficult to change the internal structure of a class without having to rewrite everything that calls it. Reproduce code: --------------- class Test { function blah () { return array(1,2,3); } function childTest () { return new Test; } } Expected result: ---------------- $test = new Test; // This does not work: $foo = $test->blah()[0]; // Instead have to do: $temp = $test->blah(); $foo = $temp[0]; // Similarly for objects, cannot do: $foo = $test->childTest()->blah(); // Instead have to do: $temp = $test->childTest(); $foo = $temp->blah();