即使变量是全局变量,变量也不能在PHP中的函数下工作

I try to define variable and then call it in my function, and then i call the function in another file. So, the variables outside the function work properly, but when i call them in function they don't work. Here's the code.

$info = new ServerInfo($server->GetServerData('IPAdress'));
$id = $server->GetServerData('ID');
$sshhost = $server->GetServerData('SSHHOST');
$sshport = $server->GetServerData('SSHPORT');
$sshuser = $server->GetServerData('SSHUSER');
$sshpw = base64_decode(base64_decode($server->GetServerData('SSHPW')));
$port = $server->GetServerData('PORT');

/* Start Server Function */
function start_server($sshhost, $sshport, $sshuser, $sshpw){

global $sshhost;
global $sshport;
global $sshuser;
global $sshpw;
global $id;
global $port;

if (!function_exists("ssh2_connect")) return "SSH2 PHP extenzija nije instalirana";

if(!($con = ssh2_connect($sshhost, $sshport))){
    return "Ne mogu se spojiti na server";
} else {

    if(!ssh2_auth_password($con, $sshuser, $sshpw)) {
        return "Netačni podatci za prijavu";
    } else {

        $stream = ssh2_shell($con, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS);
        fwrite( $stream, "cd /home/cs && screen -A -m -S srv".$id. " ./hlds_run -console -game cstrike +port " .$port. " +map de_dust2 +maxplayers 32 -pingboost 1".PHP_EOL);
        sleep(1);
        echo "Server Startovan";

        return TRUE;

    }
}   
}
dqp99585
dqp99585 可能与您具有与变量名称相同的函数参数这一事实有关。如果可以的话,尽量不要使用全局变量。
大约 2 年之前 回复
dougan4663
dougan4663 你将它们作为参数传递并将它们声明为全局。做一个或另一个。(最好是作为参数。)
大约 2 年之前 回复

1个回答



您可以使用 $ GLOBALS ['variablename'] </ code>声明它们,然后仍然使用 $ variablename </ code>在其他函数中。
ref:
https://www.w3schools.com /php/php_superglobals.asp
如何声明 php中的全局变量? </ p>

  function start_server($ sshhost,$ sshport,$ sshuser,$ sshpw){

$ GLOBALS ['sshhost'] = $ sshhost;
$ GLOBALS ['sshport'] = $ sshport;
$ GLOBALS ['sshuser'] = $ sshuser;
$ GLOBALS ['sshpw'] = $ sshpw;

/ * do 更多东西* /
</ code> </ pre>
</ div>

展开原文

原文

You can declare them using $GLOBALS['variablename'] then still use the $variablename in other function. ref: https://www.w3schools.com/php/php_superglobals.asp How to declare a global variable in php?

function start_server($sshhost, $sshport, $sshuser, $sshpw){

$GLOBALS['sshhost'] = $sshhost;
$GLOBALS['sshport'] = $sshport;
$GLOBALS['sshuser'] = $sshuser;
$GLOBALS['sshpw'] = $sshpw;

/* do more stuff */

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐