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

What is the difference between declaring a variable inside a function like globalor public/privateVS, passing it to the function as an argument?

Another related confusion

I recently caused a big headache, trying to pass the aa array variable to a function as globalwell as edit it inside and hope to return it, and it took me several hours to realize that I needed to pass it to the function as an argument by reference, for examplefunctionCall(&$arrayVar);

Secondary question: But I'm still wondering why it doesn’t work to pass the variable as a quality global, then edit it and return it with returnor just by doing something like concatenation into an array of variables?

Another example that I recently encountered is creating a function for PHPMailer, where I pass it a few arguments, such as an email address and message body, but I also need to pass authentication strings, such as an API key, etc. Here, every time I call him:

  • I don’t want to give him authentication credentials every time I call the PHMailer function (for example, send an email error message in one of several stages)
  • But I want to give him unique arguments every time I call him

, , :

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");

: global , ?

+2
1

, ...

/ VS, ?

global - . global , . , , , , mystery.

public, private, protected visibility, - . , .

, ,

-, , , , , .

, global, return - ?

return a global, . , .

, , PHPMailer, , , , API ..

global. , , , constant, :

define('AUTH', 'my_key');
function phpMailer( $mail_to = "to@email.com", $mail_from = "a@b.com" ) {
    echo AUTH;
}

, , . , , :

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');

, . - PHP, , .

+2

Source: https://habr.com/ru/post/1649090/


All Articles