PHP: Calling function from another class issue

Discussion in 'Coding Help' started by ziycon, Jan 6, 2011.

Tags:
  1. ziycon

    ziycon New Member

    I'm calling a function from another class and instead of creating a new object every time which is the easiest way I was trying to create the object in the constructor and set it to a global var for the class and then call functions when need, something like below.

    Code:
    class one {
        var $object;
    
        public function __construct() {
            $this->object = new two();
            $this->test();
        }
    
        private function test() {
            $var = $this->object->funcInClassTwo();
        }
    }
    This is the other way but would involve creating an object for each function that required the function in the second class.
    Code:
    class one {
        public function __construct() {
            $this->test();
        }
    
        private function test() {
            $object = new two();
            $var = $object->funcInClassTwo();
        }
    }
    Just looking for advice on the best way forward, thanks.
     
  2. ziycon

    ziycon New Member

    I've gotten it working using the first example code snippet above but I'm still interested to see what people think is the best way to go about this, create a single object for the class or create an object for each function as needed?
     
  3. MOH

    MOH New Member

    If you're only instantiating the classTwo object to call that function, wouldn't you be better off changing classTwo and declaring the function as static?
     

Share This Page