Jump to content

Using an initialzed class inside a funtion without using global


djones

Recommended Posts

What is the best way to accomplish this? I need to reuse a class inside a function. Is it ok on performance to intialize the class again in the function? See below.

 

$oClass = new cClass();

// ... Use class for tasks ...

// Use class in function without passing $oClass
// Want to do this without having to initialize the class again. OR is this OK?
function nav($id){
  // Would not like to initialize class again.
  // $oClass = new cClass()
   // do stuff with $oClass

}

// I do not want to do this
function nav($id, $oClass)[

   // Do stuff with $oClass
}

One reason he may not want to (which I am not 100% sure happens) is passing it as an argument creates a new object?

 

You may want to try and make the class global

 

global $oClass;
$oClass = new class();

function new($id) {
     global $oClass;
}

 

However, like I said, I am not sure if this is what you want or if it is considered good practice, but it is another option for you.

The reason why I do not want to pass it in the function is because the function will be a configuration function for a user, I was trying to make is as clean as possible. I did not want the user to have to worry about what the other variable was for.

 

// easier for user
function nav($id){}

// Do not wish todo
function nav ($id, $oClass){}

 

With that, is a global safe? Or should I re-initialize the class again in the function?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.