加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中引用容器对象的方法?

发布时间:2020-12-13 13:18:18 所属栏目:PHP教程 来源:网络整理
导读:在 PHP中给出以下内容: ?phpclass foo { public $bar; function __construct() { "Foo Exists!"; } function magic_bullet($id) { switch($id) { case 1: echo "There is no spoon! "; case 2: echo "Or is there... "; break; } }}class bar { function __
在 PHP中给出以下内容:
<?php
class foo {
  public $bar;
  function __construct() {
    "Foo Exists!";
  }

  function magic_bullet($id) {
    switch($id) {
    case 1:
      echo "There is no spoon! ";
    case 2:
      echo "Or is there... ";
      break;
    }
  }
}

class bar {
  function __construct() {
    echo "Bar exists";
  }
  function target($id) {
    echo "I want a magic bullet for this ID!";
  }
}

$test = new foo();
$test->bar = new bar();
$test->bar->target(42);

我想知道’bar’类是否可以调用’foo’类的’magic bullet’方法. ‘bar’实例包含在’foo’实例中,但与它没有父/子关系.实际上,我有很多不同的“条形”类,“foo”在一个数组中,每个类都有一些与$id不同的东西,然后想要将它传递给“magic_bullet”函数以获得最终结果,因此禁止结构更改类关系,是否可以访问“容器”实例的方法?

您必须修改代码才能提供关系.在OOP中,我们称之为 aggregation.

假设PHP 4,以及“一系列条形图”的想法

<?php

class foo {
  var $bars = array();
  function __construct() {
    "Foo Exists!";
  }

  function magic_bullet($id) {
    switch($id) {
    case 1:
      echo "There is no spoon! ";
    case 2:
      echo "Or is there... ";
      break;
    }
  }

  function addBar( &$bar )
  {
    $bar->setFoo( $this );
    $this->bars[] = &$bar;
  }
}

class bar {
  var $foo;
  function __construct() {
    echo "Bar exists";
  }

  function target($id){
    if ( isset( $this->foo ) )
    {
      echo $this->foo->magic_bullet( $id );
    } else {
      trigger_error( 'There is no foo!',E_USER_ERROR );
    }
  }
  function setFoo( &$foo )
  {
    $this->foo = &$foo;
  }
}

$test = new foo();
$bar1 = new bar();
$bar2 = new bar();

$test->addBar( $bar1 );
$test->addBar( $bar2 );

$bar1->target( 1 );
$bar1->target( 2 );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读