Re: Assigning functions

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, May 2, 2008 at 1:09 PM, Philip Thompson <philthathril@xxxxxxxxx>
wrote:

> Hi all. I have several classes. Within each class, a new class is called.
> Is there a way to assign a function in a *deeper* class to be called in the
> first class? Example to follow......
>
> <?php
> class A {
>    function __construct () {
>        $this->b = new B ();
>        // I want to do the following. This does not work, of course.
>        $this->doSomething = $this->b->c->doSomething;
>    }
> }
>
> class B {
>    function __construct () {
>        $this->c = new C ();
>    }
> }
>
> class C {
>    function __construct () { }
>    function doSomething () { echo "¡Hi!"; }
> }
>
> $a = new A ();
> // Instead of doing this,
> $a->b->c->doSomething();
>
> // I want to do this.
> $a->doSomething(); // ¡Hi!
> ?>
>
> Basically, it's just to shorten the line to access a particular function.
> But, is it possible?!


i cant remember what the term is for it phillip (ill look later), but thats
sort of considered a bad practice..  primarily since c is composed by b and
a doesnt really know about it, then the way a should talk to c is through
b.  so i would create a wrapper method in b (you have many implementation
options here) as a simple example something like this

class B {
  //...
  function doSomething() {
      return $this->c->doSomething();
  }
}

which allows you this in A instances

$this->b->doSomething();

this is the preferred approach, since A and C instances are loosely coupled.

of course, if you wanted a to 'know' about c then you could do something
like this,

class B {
  // ..
  function getC() {
     return $this->c;
  }
}

giving you the ability to do this in A instances

$this->b->getC()->doSomething();

of course now A's knows about C's and your system is more tightly coupled.

-nathan

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux