Pbearne
Pbearne

Reputation: 1165

calling a function of a class created in class in php

Here is the code layout outline all nicely laid out in 3 file and class's

$aa = new className();
class className {
    /**
    * Constructor
    */
    function className() {
        $this->init_SubClass();
    }

    function init_SubClass() {
        require_once('sub_class.class.php');
        $sub_class = new sub_class();
    }
}

sub_class.class.php

   class sub_class {
    /**
    * Constructor
    */
    function sub_class() {
        $this->init_Sub_Sub_Class();
    }

    function init_Sub_Sub_Class() {
        require_once('Sub_Sub_Class.class.php');
        $Sub_Sub_Class = new Sub_Sub_Class();
    }
}

sub_sub_class.class.php

class Sub_Sub_Class {
    public function function_I_to_call() {
        echo ' show this text'
    }
}

How to a call function_I_to_call()

This was mybest guess so far

$aa->className->sub_class->function_I_to_call()

Not sure how to do this or if it can be done.

Many Thanks

Upvotes: 1

Views: 68

Answers (1)

Gordon
Gordon

Reputation: 317197

You are not assigning the newly created object to the instance. You need to use

$this->sub_class = new Subclass;

That will make them public properties and then you can use your

$aa = new className;
$aa->sub_class->function_I_to_call();

However, the entire approach is completely flawed:

Alternate approach

class Foo
{
    protected $bar;
    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }
    public function getBar()
    {
        return $this->bar;
    }
}

And then Bar

class Bar
{
    protected $baz;
    public function __construct(Baz $baz)
    {
        $this->baz = $baz;
    }
    public function getBaz()
    {
        return $this->baz;
    }
}    

And Baz:

class Baz
{
    public function fn()
    {
        return 'called';
    }
}

And then assemble it via:

$foo = new Foo(new Bar(new Baz));

Or move that code to a Factory:

class FooFactory
{
    public function create()
    {
        return new Foo(new Bar(new Baz));
    }
}

Finally, the Autoloader (simplified):

spl_autoload_register(function($className) {
    $classMap = array(
        'Foo' => '/path/to/Foo.php',
        'Bar' => '/path/to/Bar.php',
        'Baz' => '/path/to/Baz.php',
    );
    require $classMap[$className];
});

And then you could call (demo)

$fooFactory = new FooFactory;
$foo = $fooFactory->create();
echo $foo->getBar()->getBaz()->fn();

But you shouldnt (unless it's some sort of DSL), because that is violating Law of Demeter because you are digging too deep into the collaborators.

Upvotes: 5

Related Questions