2014-02-23 48 views
0

我有一組PHP變量(以$cta開頭)。我使用PHP'If'測試,根據其他變量的值更改這些變量的值。PHP:訪問存儲在函數中的變量

我在我的PHP文件中的幾個位置使用這些變量(並根據位置將變量包含在不同的HTML代碼中),所以我想在函數中存儲'If'測試代碼。

這樣,我的代碼會更有效率,因爲'If'測試將在一個地方。

這裏是我的功能:

function calltoaction { 

if ($cta_settings == 'cta_main') { 
       $cta_prompt = 'We are ready for your call'; 
       $cta_button = 'Contact Us'; 
      } 
($cta_settings == 'cta_secondary') { 
       $cta_prompt = 'Call us for fast professional service'; 
       $cta_button = 'Call Us'; 
      } 
} 

現在,我具備的功能,怎樣訪問它裏面的$ CTA變量?

E.g.以下不起作用:

<?php 
calltoaction(); 
print '<p>' . $cta_prompt . '</p>; 
print '<span>' . $cta_button . '</span>; 
?> 

(上面介紹的例子是削減版本,我的完整代碼有點複雜)。

+0

聲明'$ cta_prompt'爲全局變量 –

+0

'全局變量$ cta_prompt,$ cta_button;'(內部功能) – cornelb

+4

不要使用全局變量,無論是之前的評論提供了非常糟糕的建議。 – meagar

回答

1

也許你想要做這樣的事情:

<?php 
function callToAction($cta_settings) 
{ 

    if ($cta_settings == 'cta_main') { 
     $cta_prompt = 'We are ready for your call'; 
     $cta_button = 'Contact Us'; 
    } elseif ($cta_settings == 'cta_secondary') { 
     $cta_prompt = 'Call us for fast professional service'; 
     $cta_button = 'Call Us'; 
    } else { 
     $cta_prompt = 'Call us for fast professional service'; 
     $cta_button = 'Call Us'; 
    } 
    return ["cta_prompt" => $cta_prompt, "cta_button" => $cta_button]; 
} 

$cta1 = callToAction('cta_main'); 
?> 

<p><?php echo $cta1['cta_prompt']; ?></p> 
<span><?php echo $cta1['cta_button']; ?></span> 
5

既然我有這個功能,我該如何訪問裏面的$ cta變量呢?

你不知道。這不是功能如何工作。你還有第二個bug,因爲$cta_settings不會被設置在你的函數中,因爲你沒有傳入它或將它聲明爲全局的,這意味着你的提示/按鈕變量永遠不會被設置。

您的功能應接受輸入並返回輸出。如果你想通過函數傳遞一個值在其他地方使用,你應該使用return它。如果您需要返回複雜結果,請使用數組或對象。

您應該而不是使用全局變量。使用全局變量打破了函數打算提供的封裝。

在你的情況,我會用這樣的:

function calltoaction($settings) { 
    if ($settings == 'cta_main') { 
    return array('We are ready for your call', 'Contact Us'); 
    } else if ($settings == 'cta_secondary') { 
    return array('Call us for fast professional service', 'Call Us'); 
    } 
} 

list($prompt, $button) = calltoaction($cta_settings); 

注意該函數接受一個參數($settings),而不是引用一些全局變量,並在調用代碼中使用返回兩個值。由調用代碼決定其變量名爲本地變量,因爲它應該是 - 該函數不應該將變量注入全局範圍。

+0

如何單獨訪問提示和按鈕部分,在HTML中(我不能在函數中包含HTML,因爲每次使用該函數都會有所不同)。 –

+1

@big_smile在上面的代碼之後,它們可以單獨作爲變量調用'$ prompt'和'$ button'。這就是'list'的作用,將數組分解爲一組變量。 – meagar