1

I have a few classes, initiated on index.php, like so:

<?php
require_once('./classes/core.class.php');
require_once('./classes/forum.class.php');
$core = new core();
$forum = new forum();
?>

Is there any way to use $core within $forum? I can do it by using core::functionName() but not by $core->functionName().

The classes are:

<?php
class forum{
    public function functionName(){

I can access it by defining the class again within each function

public function functionName(){
    $core = new core();

Thanks in advance

2
  • What do you mean $core within $forum? With the code you provided, $core->functionName() should work just fine. Where does $forum come into play? Commented Dec 30, 2011 at 13:36
  • The class example I gave should be forum, rather than core. Updating it now. Commented Dec 30, 2011 at 13:43

2 Answers 2

3

You can e.g. pass the core object to the constructor of the forum class and store it as a member.

$forum = new forum($core);


class forum {
  protected $core = null;
  public function __construct(core $core) {
    $this->core = $core;
  }

  public function foo() {
    $this->core->foo('forum');
  }
}

There are other ways to make one object accessible within another, but this is one of the simpler yet feasible solutions.
see https://en.wikipedia.org/wiki/Dependency_injection

Sign up to request clarification or add additional context in comments.

Comments

0

You could inject it, look this example

class forum {
    public function hello() {
        return "Hello";
    }
}

class core {
    private $forum;

    public function setForum($forum) {
        $this->forum = $forum;
    }

    public function helloFromForum() {
        echo $this->forum->hello();
    }
}

$f = new forum();
$c = new core();

$c->setForum($f);
$c->helloFromForum();

Similar way if you like frameworks, it's Zend Registry http://framework.zend.com/manual/en/zend.registry.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.