Jump to content

[SOLVED] Use External Variable


jaymc

Recommended Posts

How can I use external variables within a function. At the moment I am having to use global $varname; for every single var I need to use within that function e.g.

 

 

	function block_build($id) {

	global $session;
	global $gallery_user;
	global $link;
	global $gallery_name;
	global $front_image;
	global $rounded_top;
	global $rounded_bottom;
}

Link to comment
Share on other sites

You could encapsulate whatever functionality this is inside a class with properties.  Then you don't have to pass anything around and each function has access to them.

Judging from his question, I am not sure he is ready to take on OOP, but sure, this is also a possibility.
Link to comment
Share on other sites

Don't use the global keyword to pass variables into functions - it prevents writing recursive functions, it prevents using default values for optional parameters, and it makes your code hard to debug a short time after you have written it because you won't remember which variables you need to setup before calling any function (for those of use that have more than one or two user written functions to keep track of.)

 

Do use parameters to pass variables into functions - is allows writing recursive functions, it allows default values for optional parameters, and it makes your code easier to debug because you can see by just reading the function call what values are being used and if you named them appropriately, you don't need to continually go back and read the function definition to figure out what they mean.

 

If you have some variables that are so closely related to a function that the global keyword makes sense, you should probably be using a class instead of functions.

Link to comment
Share on other sites

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.