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”类的“magicBullet”方法。 “bar”实例包含在“foo”实例中,但与其不存在父/子关系。实际上,我在数组中拥有“foo”拥有的许多不同的“bar”类,每个类在想要将其传递给“magic_bullet”函数以获得最终结果之前都会对 $id 执行不同的操作,因此除非使用结构类关系发生变化,是否可以访问“容器”实例的方法?
您必须修改代码才能提供关系。用 OOP 的话说,我们称之为聚合 http://en.wikipedia.org/wiki/Object_composition#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 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)