1

I'm trying to share methods between objects that belong to a parent object.

I have a main object, which has child objects that handle different tasks. These are created using the main objects constructor:

class engine {

  public function __construct() {

    $this->db = new db();
    $this->url = new url();
    $this->template = new template();

  }

}

Here's an example of how I would use my main object:

$engine = new engine();

$engine->db->connect();
$engine->url->parse();
$engine->template->render();

How could the child objects access the methods of the other children (e.g. how could template->render() call url->parse()) ?

Sean Powell
  • 1,397
  • 1
  • 9
  • 17
  • 3
    Your design is broken. Why would a template object, which responsibiliy apparently is to render something have to call url->parse? If you have an explanation for that, the answer to your question is use [Dependency Injection](http://stackoverflow.com/questions/6094744/dependecy-hell-how-does-one-pass-dependencies-to-deeply-nested-objects/6095002#6095002). – Gordon Sep 25 '11 at 13:19
  • That was a bad example I gave. In my design, the selection of the template rendered is going to depend on the requested URL from time to time (so I'd like to parse through the URL object, rather than recreate something within the template definition). Dependency Injection was what I was looking for, so thank you. – Sean Powell Sep 25 '11 at 13:34
  • 1
    You might also be interested in [SOLID](https://secure.wikimedia.org/wikipedia/en/wiki/Solid_%28object-oriented_design%29) and [GRASP](https://secure.wikimedia.org/wikipedia/en/wiki/GRASP_%28object-oriented_design%29) and the [Law of Demeter](https://secure.wikimedia.org/wikipedia/en/wiki/Law_of_Demeter) and [The Clean Code Talks](http://www.youtube.com/results?search_query=The+Clean+Code+Talks&aq=f) – Gordon Sep 25 '11 at 13:38

1 Answers1

0

You can set static property of a class and call it staticaly:

static public function parse() {
    <some code>
}

and call it like Url::parse(); from $template->render();

s.webbandit
  • 16,332
  • 16
  • 58
  • 82
  • OP asked about OOP not about Class based programming and/or how to detroy the maintainability of your application by tight coupling it.See http://kore-nordmann.de/blog/0103_static_considered_harmful.html – Gordon Sep 25 '11 at 14:30
  • If you didn't recognized, the question was: "How could the child objects access the methods of the other children". So this is how they can. – s.webbandit Sep 25 '11 at 14:31
  • yeah, in the most suboptimal way possible. If you do it this way you can just as well ditch the objects altogether and use procedural programming. – Gordon Sep 25 '11 at 14:32