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

标签 php

在 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”类,每个类在将它传递给“magic_bullet”函数以获得最终结果之前都做了一些与 $id 不同的事情,所以禁止结构类关系的变化,是否可以访问“容器”实例的方法?

最佳答案

您必须修改代码以提供关系。在 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 );

关于php - 在 PHP 中引用容器对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1240322/

相关文章:

php - SilverStripe $summary_field 中断标签翻译

php - 0A 在使用 PHP 检索时添加到 BLOB

php - 压缩包含 php、javascript、html 和 css 的网页

php - 使用变量 PHP 向正确的用户发送电子邮件

javascript - 数据表无法得到响应

php - 当名称为空时,如何从下面的代码中删除最后一个数组

php - 与类 CakePHP Bootstrap 链接的跨度类

php - 获取用户ip地址的函数

php - 如何解决magento1.9.1.0这个错误

php - 使用 mod_rewrite 重写对父目录的请求