note 126194 added to language.references.pass

From: Date: Fri, 25 Jun 2021 07:51:46 +0000
Subject: note 126194 added to language.references.pass
Groups: php.notes 
Request: Send a blank email to php-notes+get-216547@lists.php.net to get a copy of this message
I designed a class that can easily pass references. <?php #### Problem 1 function problem(&$value) { } problem(1); // cannot be passed by reference #### Problem 2 class problem2 { static function __callStatic($name, &$arguments) // cannot take arguments by reference { } } ?> My solution 👇 <?php class Reference { function __construct(public mixed &$data) { } /** * create * * @param mixed $data * @return self */ static function &create(mixed &$data): self { if ($data instanceof self) { return $data; } $r = new self($data); return $r; } /** * get value * * @param mixed $reference * @return mixed */ static function &get(mixed &$reference): mixed { if ($reference instanceof self) { return $reference->data; } return $reference; } } #### Problem solving 1 #### function test($value) { $value = &Reference::get($value); // values OR reference $value = "test-$value"; return $value; } echo test(1), PHP_EOL; // test-1 $val = 2; echo test(Reference::create($val)), PHP_EOL; // test-2 echo $val, PHP_EOL; // test-2 #### Problem solving 2 #### class TestCall { static function __callStatic($name, $arguments) { $value = &Reference::get($arguments[0]); $value = "$name-$value"; return $value; } } echo TestCall::test(3), PHP_EOL; // test-3 $val = 4; echo TestCall::test(Reference::create($val)), PHP_EOL; // test-4 echo $val, PHP_EOL; // test-4 ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 112.227.86.149) ---- Manual Page -- https://php.net/manual/en/language.references.pass.php Edit -- https://main.php.net/note/edit/126194 Del: integrated -- https://main.php.net/note/delete/126194/integrated Del: useless -- https://main.php.net/note/delete/126194/useless Del: bad code -- https://main.php.net/note/delete/126194/bad+code Del: spam -- https://main.php.net/note/delete/126194/spam Del: non-english -- https://main.php.net/note/delete/126194/non-english Del: in docs -- https://main.php.net/note/delete/126194/in+docs Del: other reasons-- https://main.php.net/note/delete/126194 Reject -- https://main.php.net/note/reject/126194 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#216547) next »