簡體   English   中英

將動態參數傳遞給函數

[英]Passing dynamic parameters into a function

假設我有一個名為ssh_connect的函數,該函數以服務器SSH設置作為參數。現在我有多個服務器,我想隨機選擇其中一台服務器並將其作為參數輸入到函數中。此外,如果使用一組SSH時$ result為空參數,必須使用其他設置

$result=ssh_connect($ip, $user, $pass, $port,$command)

假設我有以下詳細信息

//Server 1 


$ip="123.456.78.901";
$user="root"
$pass="mypassishere"
$port = "22"

//Server 2
$ip="225.456.98.901"
$user="root"
$pass="mypassishere"
$port = "22"

我可以使用選擇結構,但該解決方案存在嚴重缺陷,因為一台服務器始終會優先於其他服務器。這就像$result為空且其中包含服務器1的詳細信息一樣,請移至服務器2,這實際上不是我想要的。

我正在考慮數組,但是我不確定如何完成,因為我需要隨機選擇一組詳細信息,如果一組失敗,請嘗試另一組,直到沒有服務器或$ result有了值。

我認為您正在尋找aray_rand ,PHP網站指出

Picks one or more random entries out of an array,
and returns the key (or keys) of the random entries.

如果設置失敗,請取消設置由array_rand()返回的鍵,繼續循環直到連接成功或失敗

@gwillie的答案,下面是一個示例:

<?php
$a = array(
    array('host'=>'host1','user'=>'user1','pwd'=>'pwd1'),
    array('host'=>'host2','user'=>'user2','pwd'=>'pwd2'),
    array('host'=>'host3','user'=>'user3','pwd'=>'pwd3'),
    array('host'=>'host4','user'=>'user4','pwd'=>'pwd4'),
    array('host'=>'host5','user'=>'user5','pwd'=>'pwd5'),
);
$connect = false;
while (!$connect) {
    $srvIndex = array_rand($a);
    $host = $a[$srvIndex];
    $connect = my_connect_function($host); //Return true on success, false on error
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM