Calling a Class inside a Class
Posted: Tue Sep 14, 2004 12:17 pm
Can I do that and is it just like calling a regular class? I know the extends to add a class but I am needing to add 2 classes.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
<?php
class a
{
var $b;
function say()
{
echo $this->b->foo();
}
}
//
class b
{
function foo()
{
return "u foo";
}
}
//
$a = &NEW a();
$b = &NEW b();
$a->b = &$b;
$a->say();
?>Code: Select all
/*
Aggregation:
*/
class A
{
function A(&$aggregated_class)
{
$this->aggregated_class =& $aggregated_class;
}
function foo()
{
// accesses $aggregated_class interface
}
}
$an_object =& new WhateverItIs();
$another_object =& new A($an_object);
$another_object->foo();
/*
Composition (the Factory pattern)
*/
class B
{
function B()
{
$this->_setFactoryObject();
}
function foo()
{
// accesses $factory_object interface
}
//////////////////////////////////////////
// PRIVATE //
//////////////////////////////////////////
function _setFactoryObject()
{
$this->factory_object =& new WhateverItIs();
}
}
$object =& new B;
$object->foo();wouldn't A::aggregated_class be a reference to a copy of an object of WhateverItIs? (PHP4) Shouldn't A's constructor take a reference to first argument?McGruff wrote:Code: Select all
class A { function A($aggregated_class) { $this->aggregated_class =& $aggregated_class; } function foo() { // accesses $aggregated_class interface } } $an_object =& new WhateverItIs(); $another_object =& new A($an_object); $another_object->foo();