0

I have a code structure like this:

class myclass{

    use App/classes/Log

    public function myfunc1 () {

        $log_obj = new Log;
        $log_obj->log('something1');    

    }
    public function myfunc2 () {

        $log_obj = new Log;  
        $log_obj->log('something2');   

    }
    public function myfunc3 () {

        $log_obj = new Log;  
        $log_obj->log('something3');   

    }
}

In reality, I have 12 methods which I need to make a object of Log class in the most of them. Now I want to know, isn't there any better approach to I do that (making an object) once? For example using a static property and setting the object to it or whatever ..

stack
  • 10,280
  • 19
  • 65
  • 117
  • If the method that you need to call isn't static - then creating an object like you are doing is the way to go. – ChristianF Dec 25 '16 at 06:24
  • Possible duplicate of [Creating the Singleton design pattern in PHP5](http://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5) – Matt Clark Dec 25 '16 at 06:25
  • Why don't just assign the Log instance to a property of myclass and use it in those functions like $this->log? – Igor Skoldin Dec 25 '16 at 06:26
  • @IgorSkoldin [I've already tested it](https://3v4l.org/5Yi2j) .. wont work. – stack Dec 25 '16 at 06:27
  • Oh - I think I misunderstood the question. You could limit the creation of the Log object to just 1 by using the Singleton pattern for the Log class. Esentially you have a private constructor and a public method that will return a new instance of a Log object if there hasn't already been one created – ChristianF Dec 25 '16 at 06:29
  • @Chris Yes .. I'm trying to implement what you said kinda .. – stack Dec 25 '16 at 06:30
  • @stack, this won't but if you use __construct for this it should. – Igor Skoldin Dec 25 '16 at 06:35

1 Answers1

1

You can assign the Log instance to a property of your myclass using __construct. Here's an example of accessing a method of a class inside another class:

class Test {
    public $var = 'test';

    public function show_var() {
        echo $this->var;
    }
}

class Test_2 {
    protected $test;

    public function __construct() {
        $this->test = new Test;
    }

    public function show_test() {
        $this->test->show_var();
    }

}

$test_2 = new Test_2;

$test_2->show_test();

See here in action.

Igor Skoldin
  • 730
  • 3
  • 12
  • 25