Jump to content

Using an initialzed class inside a funtion without using global


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?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.