Please explain the difference between function($variable) and function() - php

I have two scripts: the first script receives data via socket and does some stuff with it, the second script holds a function that gets called by the first script. The function happens to make use of a variable created in the first script.
When calling the function from the first script, should I run it like this:
include 'secondscript.php';
//socket stuff, create $variable from input received
functionName()
Or like this:
include 'secondscript.php';
//socket stuff, create $variable from input received
functionName($variable)
I understand that one is a "global" declaration, but I'm having trouble understanding the significance of that. And of course, I'm wondering if that is what's causing something not to work.
Thanks very much.

You really need to read up on the basics of functions.
functionName();
means you are requesting a function and passing no information to it.
functionName($someVar);
means you are sending it the information in the $someVar variable.

Expanding on the above:
The difference is simply the arguments passed. You can access variables through the global declaration within a function, but personally, I think it is a bad idea.
You will always want to know what arguments and types are being passed to and from a function. At least, if you don't want to define the arguments in the function definition, but still pass them as an argument to the function call, you can grab the passed args via something like func_get_args():
// definition
function funca(Array $arr){
// This tells funca to only allow Arrays as the arg type
}
// definition
function funb(){
$args = func_get_args();
// You dont define args, but can still pull them.
}
//call
funcb('a', 'b');

Related

How to pass a variable into multiple functions

In my screenshot below you can see I have a list of functions that run a routine, fairly in-depth routine.
Previously, I have ben repeating this routine in multiple classes, but now I would like to consolidate those multiple classes into one class and execute only one function, by passing a variable into that function to determine the output to return.
I know how to pass the variable into "one" function, but how can I pass the variable ($this_id) into my multiple functions below? Basically, whatever $this_id is from get_output($this_id); I want that same variable value to be carried over into the other $this_id functions. See screenshot...
I searched online and all answers I've seen show how to do this in a non static way, but I'm only familiar with calling things statically, really. I tried the obj way, but couldn't get it to work.
Example, execution...
$header = 'CustomTheme_output';
$header::get_output('header');
(please disregard any lose code, the code is what I have so far from trying multiple ways. private $id and __construct are from the online solutions I have been trying)
Could you please clue me in on how I can correctly achieve this? I would be sooo happy to get rid of all the repetitive code, folders and files I have! - Thanks!
Either you pass it directly into each method call:
public function foo($this_id) {
$this->bar($this_id);
}
Or you make it a class attribute, and simply ACCESS it from the various methods:
public function foo($this_id) {
$this->id = $this_id;
$this->bar();
}
public function bar() {
do_something($this->id);
}

In PHP, what is the difference between declaring a variable as global inside function, or passing the variable as an argument to the function?

What is the difference between declaring a variable within a function as global or public/private VS passing it to a function as an argument?
Other related confusion
I've recently caused myself a big headache trying to pass aa array variable into a function as global and editing it inside and hoping to return it altered, and it took me hours to figure out that I needed to pass it into the function as an argument by reference, like functionCall(&$arrayVar);
Secondary question: But I am still wondering, why doesn't it work to pass the variable in as global then edit it and spit it back out with return or simply by doing something like concatenating to the variable array?
Another example I recently ran into is by making a function for PHPMailer, where I am passing it several arguments, like email-to address and message body, but I also need to pass it authentication strings, like API key, etc. Here, each time I call it:
I don't want to have to pass it the authentication credentials every time I call the PHMailer function (eg, to email error message at one of several stages)
But I do want to pass it unique arguments every time I call it
So I figured the best way is like this:
function phpMailer( $mail_to = "to#email.com", $mail_from = "a#b.com" ) {
global $authCredentials;
}
// And of course, when I call phpMailer, I call it like
phpMailer("that.guy#there.com", "me#here.com");
Tertiary question: Is this appropriate usage of global or is there some other way I should be doing this?
There are a lot of questions here, I will try to walk through them...
What is the difference between declaring a variable within a function as global or public/private VS passing it to a function as an argument?
global is a type of variable scope. Declaring a variable as global is generally considered bad practice and you should try to avoid it. By passing the variable to a function as an argument, the code is more reusable because you know what the function expects and it isn't relying on some unknown mystery global variable.
public, private, protected are types of visibility used in object oriented programming. These basically determine how properties and methods within a class can be accessed by other classes.
it took me hours to figure out that I needed to pass it into the function as an argument by reference
Something to understand about functions is that unless you pass arguments by reference you are working with a copy of the variable, not the original.
why doesn't it work to pass the variable in as global then edit it and spit it back out with return or simply by doing something like concatenating to the variable array?
You wouldn't need to return a global variable, because you're working with the original value. Please refer again to the link above about scope.
Another example I recently ran into is by making a function for PHPMailer, where I am passing it several arguments, like email-to address and message body, but I also need to pass it authentication strings, like API key, etc.
There are several ways to approach this in addition to using global. If you are planning to use this authentication key in more than one place, the easiest solution would probably be to define a constant, for example:
define('AUTH', 'my_key');
function phpMailer( $mail_to = "to#email.com", $mail_from = "a#b.com" ) {
echo AUTH;
}
But again, the function is now less reusable because it is dependent on that constant. A better solution would probably be to wrap it in an object:
class phpMailer()
{
private $auth = 'my_key';
public function send($mail_to, $mail_from)
{
$this->auth;
}
}
$mail = new phpMailer();
$mail->send('to#email.com', 'a#b.com');
Hopefully this helps. The online PHP documentation found in the links above contain a wealth of information.

PHP - How to handle method calls

Which is the better way to handle the following case? I've been wondering about this for a while and figured I'd ask.
Define a variable?
$getItems = $itemTools->getItems($item_id);
if($getItems)
{
//do stuff
}
Or
if($itemTools->getItems($item_id))
{
//do stuff
}
IMHO it would depend on what you were doing after/within the if branch. If your plan is doing something with the returned data then it makes sense to me storing the results in a var. Otherwise it doesn't.
Looking at the function name I'm assuming it is not a simple check but a function returning 'usable' data so probably you will use this data and you actually need the var.
Unless you are doing this in the global scope, if you are doing this within some method then php will release the memory used by this var once the method ends.
What about doing another (and quick) method named 'hasResults($itemId)' returning a boolean?
Just wondering

How to pass a parameter as a local variable into a method

This may be a very dumb question, but how can I pass a parameter as a local variable in a PHP class.
e.g (this does not work, but represents what I want)
public function sql($this->sql_statement){
// do something
}
I would like the passed parameter to become the '$this->sql_statement' variable
Obviously, I could just do this, but I want to know if there is a better way:
public function sql($statement){
$this->sql_statement = $statement;
// do something
}
To the best of my knowledge, there is no better way. As your method may be called from outside the class, you essentially need to treat it as a standard setter method: set the member variable to the value of the passed parameter, just like in your second code.

Function scopes in regards with includes in PHP

I'm having a bit of trouble understanding includes and function scopes in PHP, and a bit of Googling hasn't provided successful results. But here is the problem:
This does not work:
function include_a(){
// Just imagine some complicated code
if(isset($_SESSION['language'])){
include 'left_side2.php';
} else {
include 'left_side.php';
}
// More complicated code to determine which file to include
}
function b() {
include_a();
print_r($lang); // Will say that $lang is undefined
}
So essentially, there is an array called $lang in left_side.php and left_side2.php. I want to access it inside b(), but the code setup above will say that $lang is undefined. However, when I copy and paste the exact code in include_a() at the very beginning of b(), it will work fine. But as you can imagine, I do not wish to copy and paste the code in every function that I need it.
How can I alleviate this scope issue and what am I doing wrong?
If the array $lang gets defined inside the include_a() function, it is scoped to that function only, even if that function is called inside b(). To access $lang inside b() you need to call it globally.
This happens because you include 'left_side2.php'; inside the include_a() function. If there are several variables defined inside the includes and you want them to be at global scope, then you will need to define them as such.
Inside the left_side.php, define them as:
$GLOBALS['lang'] = whatever...;
Then in the function that calls them, try this:
function b() {
include_a();
print_r($GLOBALS['lang']); // Now $lang should be known.
}
It is considered 'bad practice' to use globals where you don't have to (not a consideration I subscribe to, but generally accepted). The better practice is to pass by reference by adding an ampersand in front of the passed variable so you can edit the value.
So inside left_side or left_side2 you would have:
b($lang);
and b would be:
function b(&$lang){...}
For further definitions on variable scopes check this out

Categories