2013-01-23 38 views
0

我已經有了這個塊,它在我的代碼中出現了一次又一次,有輕微的變化,我想使用一個函數,但據我所知,當寫一個函數時設定的參數的數量,製作一個無限數量參數的函數

使用代碼IM的塊是

$type = $xml->response->williamhill->class->type; 
    $type_attrib = $type->attributes(); 
     echo "<h2>".$type_attrib['name']."</h2>"; 
     echo "<h2>".$type_attrib['url']."</h2>"; 

的主要區別是,它通過一個XML文檔向下鑽取的第一行,它可以進一步深入,在其他地方,有可能做一個功能?

即。它可能需要像這樣一些地方:

$xml->response->williamhill->class->type->market->participant

+0

所以......爲什麼你的函數需要一個無限數量又是什麼爭論? –

+1

[從「相關」到右側。](http://stackoverflow.com/questions/4722642/is-there-a-way-to-allow-a-function-to-accept-an-indefinite-number- of-arguments?rq = 1)雖然你可能會以錯誤的方式看待它。 –

+0

任意的,不是無限的!無限數量的數據會佔用存儲空間中的所有存儲空間,並一直持續到宇宙的熱死亡處理。 – paxdiablo

回答

2

您可以使用XPath:

function get_type_as_html($xml, $path) 
{ 
    $type = $xml->xpath($path)[0]; // check first if node exists would be a good idea 
    $type_attrib = $type->attributes(); 
    return "<h2>".$type_attrib['name']."</h2>" . 
     "<h2>".$type_attrib['url']."</h2>"; 
} 

用法:

echo get_type_as_html($xml, '/response/williamhill/class/type'); 

此外,如果此路徑的任何部分都一樣,你可以移動部分進入功能,即

$type = $xml->xpath('/response/' . $path); 
+2

備註:通常,函數不應該輸出任何東西,而是返回。這就是爲什麼我將'echo'移出該函數的原因。 –

1

有沒有必要的參數無限數量。做到這一點的方法是每次調用函數時可以改變一個參數。

首先定義功能,並有$type變量參數:

function output_header($type) 
{ 
    $type_attrib = $type->attributes(); 
    echo "<h2>".$type_attrib['name']."</h2>"; 
    echo "<h2>".$type_attrib['url']."</h2>"; 
} 

然後就可以調用與任何$xml->...屬性你喜歡的功能。

<?php 
    output_header($xml->response->williamhill->class->type); 
    output_header($xml->response->williamhill->class->type->market->participant); 
?> 
相關問題