-1

I have created a PHP class and I want to access its methods from a function in another file. Below is my code:

include_once PLUGIN_DIR_PATH."/classes/Brands.php";

function create_tables(){

$brand_obj = new Brands;    
$brand_obj->create_brand_table();           
}

function delete_tables() {

$brand_obj = new Brands;    
$brand_obj->delete_brand_table();
}

Is it possible to create the object only once and then reuse it in every function? Right now, I am creating object in every function which is not a good practice.

Sameer Ali
  • 147
  • 1
  • 5
  • 13

2 Answers2

0

You can use the global keyword to use a variable created outside a function inside a function:

global $object

code example :

include_once PLUGIN_DIR_PATH."/classes/Brands.php";

$brand_obj = new Brands;

function create_tables(){

    global $brand_obj;
    $brand_obj->create_brand_table();
}

function delete_tables() {

   global $brand_obj;
   $brand_obj->delete_brand_table();
}
Ooggle
  • 1
  • 3
  • Using global variables should be avoided whenever possible. See [this post](https://stackoverflow.com/a/12446305/965834) for details. – Jeto Dec 25 '19 at 22:17
0

I'm going to assume your actual functions do more than what you posted, otherwise you don't really need functions and can simply do this:

$brand_obj = new Brands;    
$brand_obj->create_brand_table();            
$brand_obj->delete_brand_table();

Otherwise, you can make a class and inject the Brands dependency into one of its properties via its constructor:

class TablesManager
{
  private $brands;

  public function __construct(Brands $brands)
  {
    $this->brands = $brands;
  }

  public function create_tables(): void
  {
    $this->brands->create_brand_table();
  }

  public function delete_tables(): void
  {
    $this->brands->delete_brand_table();
  }
}

Usage:

$brands = new Brands();
$tables_manager = new TablesManager($brands);
$tables_manager->create_tables();
$tables_manager->delete_tables();

Note: calling a class SomethingManager is sometimes considered bad practice / a sign that the class does too many things. Consider (at least) giving it a more accurate name for your needs.

Demo: https://3v4l.org/iTmY6

Non-OOP alternative

function create_tables(Brands $brand_obj): void { 
  $brand_obj->create_brand_table();           
}

function delete_tables(Brands $brand_obj): void {
  $brand_obj->delete_brand_table();
}

$brand_obj = new Brands();    
create_tables($brand_obj);
delete_tables($brand_obj);
Jeto
  • 14,596
  • 2
  • 32
  • 46