0

My problem is this (In PHP):

I have three classes,

Class cls1 {
    public function myfunc() {

    }
}
Class cls2 {
    private $_obj1; //type of cls1
    ...
    public function getObj1() {
        return $_obj1;
    }
}

Class cls3 {
    ...
    public function getMyFunc() {
        $temp = new cls2();
        $temp->getObj1()->myfunc(); //THIS IS NOT WORKING.
        //PHP Throws an error like : Fatal error: Call to a member function getId() on a non-object in xyz.php on line 125.
    }
}

I cannot reach cls1's function from cls3 through the way cls2.

How can I implement it?

NOTE: I wrote this basic code to show the problem. Do not consider about syntax errors.

tereško
  • 58,060
  • 25
  • 98
  • 150
totten
  • 2,769
  • 3
  • 27
  • 41
  • "THIS IS NOT WORKING" --- please elaborate this. It's not possible to help you if we don't know what's the real issue – zerkms Sep 07 '12 at 12:09
  • 2
    Did you create an instance of cls1 somewhere in cls2 ? It looks you didn't created it and just returning null instead of expected instance. – zysoft Sep 07 '12 at 12:09
  • `$temp->getObj1()` probably returns `null`. is there something in `$_obj1` (cls2) – MarcDefiant Sep 07 '12 at 12:09

3 Answers3

2

You have to instatiate the $_obj1 property of the $temp object before you can retrieve it. Do that in the cls2 constructor for example. Also you need to refer to the private property correctly inside your classes, using the this keyword to refer to the instance.

Class cls2 {
    private $_obj1; //type of cls1
    ...
    public function __construct(){
        $this->_obj1 = new cls1();
    }

    public function getObj1() {
        return $this->_obj1;
    }
}
Asciiom
  • 9,867
  • 7
  • 38
  • 57
2

Object1 hasn't been instantiated yet.

Class cls1 {
    public function myfunc() {

    }
}
Class cls2 {
    private $_obj1; //type of cls1
    ...
    public function getObj1() {
        if(!$this->$_obj1 instanceof cls1) {
            $this->_obj = new cls1();
        }
        return $_obj1;
    }
}

Class cls3 {
    ...
    public function getMyFunc() {
        $temp = new cls2();
        $temp->getObj1()->myfunc(); //THIS IS NOT WORKING.
    }
}
Louis Huppenbauer
  • 3,719
  • 1
  • 18
  • 24
1

That is probably a bad way of doing it. Why making a class and instancing it in another class when you can simply extend the first class in the second class..

<?php
class cls1 {
    public function myFunc() {
        echo "I am myFunc!";
    }
}
class cls2 extends cls1 {
    public function getObj1() {
        return $obj1;
    }
}
class cls3 {
    public function getMyFunc() {
        $temp = new cls2();
        $temp->myFunc();
    }
}
$a = new cls3();
$a->getMyFunc();
?>
Miro Markaravanes
  • 3,285
  • 25
  • 32