Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: zwracanie referencji przez funkcję
Forum PHP.pl > Forum > PHP > Object-oriented programming
flashdev
  1. // test.php
  2. <?php
  3. class test{
  4. private $variable = 'default';
  5.  
  6. public function &getVariable1(){
  7. return $this -> variable;
  8. }
  9. public function getVariable2(){
  10. $ref = &$this -> variable;
  11. return $ref;
  12. }
  13. public function &getVariable3(){
  14. $ref = &$this -> variable;
  15. return $ref;
  16. }
  17.  
  18. public function __destruct() {
  19. echo $this -> variable;
  20. }
  21. }
  22. ?>


  1. <?php
  2.  
  3. include('class/test.php');
  4. $test = new test();
  5. $variable = $test -> getVariable1();
  6. $variable = 'new value';
  7. $variable = $test -> getVariable2();
  8. $variable = 'new value';
  9. $variable = $test -> getVariable3();
  10. $variable = 'new value';
  11.  
  12. ?>


Czy potrafi mi ktoś wytłumaczyć dlaczego żadna z tych funkcji nie zwraca referencji? Da się takie coś wogóle zrobić?
darko
Źle wywołujesz, zwróć uwagę na sposób wykorzystania (w przykładach) http://www.php.net/manual/pl/language.references.return.php

Czyli, np

  1. $variable = &$test -> getVariable1();
  2. $variable = 'new value';
  3. $variable = $test -> getVariable2();
  4. $variable = 'new value';
  5. $variable = &$test -> getVariable3();
flashdev
Dzięki za pomoc. Już rozumiem gdzie tkwi błąd. Funkcja 1 oraz 3 zwracała referencję prawidłowo, tylko w linijakch 1, 3 oraz 5 kopiowałem obiekt na nowo.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.