php oo引用类成员

时间:2015-10-29 16:51:17

标签: php oop reference

class Foo{
   private &$member;
   function __construct(&$member){ $this->member = &$member; }
   function doSmtg(){//changes member }
   function doSmtgElse(){//changes member }
}
$myMember = "";
foo = new Foo($myMember);
foo->doSmtg();
echo $myMember;

我想将$ mymember作为引用传递给Foo的构造函数,以便在$ myMember变量上直接更改它的更改。

我的代码目前是错误的,我收到有关意外'&'的错误在private &$member; 所以我猜我的refrence使用语法有问题吗?

我试图关注:http://php.net/manual/en/language.references.pass.php

3 个答案:

答案 0 :(得分:1)

请这样做:

class Foo{
   private $member1;
   private $member2;
   function __construct(){}
   function doSmtg($member1, $member2){
      $this->member1 = $member1;
      $this->member2 = $member2;
      //changes member1 and 2 
   }
   function doSmtgElse(){
      $this->member1 = $member1;
      $this->member2 = $member2;
      //changes member1 and 2 
   }
   function getMember1(){
      return $this->member1;
   }
   function getMember2(){
      return $this->member2;
   }
}
$myMember1 = "";
$myMember2 = "";
$foo = new Foo();
$foo->doSmtg($myMember1, $myMember2);
echo $foo->getMember1.", ".$foo->getMember2;

答案 1 :(得分:1)

你做错的第一件事是:

private &$member;

PHP中不允许这样做。 你为什么要使用参考文献?引用在PHP中的工作方式不同。 PHP引用与C或C ++等其他语言不同。

答案 2 :(得分:0)

您无法定义变量引用。您只能拥有一个包含对另一个变量的引用的变量。

除此之外,您不必告诉PHP在定义时要将哪些内容添加到变量中。

因此: public interface FragmentLifeCycle { void onPauseFragment(); } ///for saving your data you must implement it in all fragments from view Pager public class SomeFragment extends Fragment implements FragmentLifeCycle { @Override public void onPauseFragment() { //save your data here }} public class NewHomeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //......... //.......... final ViewPager.SimpleOnPageChangeListener listener = pageChangeListener(YourPagerAdapter); YourViewPager.addOnPageChangeListener(listener); } private ViewPager.SimpleOnPageChangeListener pageChangeListener(final FragmentPagerAdapter adapter) { return new ViewPager.SimpleOnPageChangeListener() { int currentPosition = 0; @Override public void onPageSelected(int newPosition) { FragmentLifeCycle fragmentToHide = (FragmentLifeCycle) adapter.getItem(currentPosition); fragmentToHide.onPauseFragment(); currentPosition = newPosition; } }; }} 可以 private &$member;