简体   繁体   中英

Create new php instance or pass it as parameter

I need the best way for these two scenarios:

I have these classes:

class classA{
   function func1() {
        echo "HELLO1 ";
   } 
   function func2() {
        echo "HELLO2 ";
   }   
}

class classB{
   function func1() {
      obj_a = new classA();
      obj_a->func1();

      $this->fun2($obj_a); // pass instance as parameter - scenario1

      //OR

      $this->func3();  // do not pass instance as parameter - scenario2 
   }

   function func2($obj_a) {
        $this->fun2($obj_a);
   }

   function func3() {
        $obj_a = new classA();
        $this->fun2($obj_a);
   }
}

$b = new classB();
$b->func1(); // HELLO1 HELLO2

which one the the best practice to use:

  1. $this->fun2($obj_a); // pass instance as parameter - scenario1
  2. $this->func3(); // do not pass instance as parameter - scenario2

What is best depends on what you need to do. Here is another useful scenerio.

class classC{
    protected $classA

    public function __construction(classA $classA) {
        $this->classA = $classA;
    }
    public function func2() {
        $this->classA->fun2();
    }
}
$classA = new classA();
$classC = new classC($classA);

If Class A methods are based on properties of the instance, all depends on wether you want to pass the instance (and therefore the property values) or if you want a freshly initialized object.

If Class A methods are not based on state of the instance, your method should be static, and you should not have to instanciate Class A at any moment :

class classA {
   public static function func1() {
        echo "HELLO1 ";
   } 
   public static function func2() {
        echo "HELLO2 ";
   }   
}

class classB {
   function func1() {
      $this->fun(); 
   }

   function fun() {
      ClassA::func1();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM