2012-06-14 42 views
1

我有以下問題。我有聲明的變量文件variable.php:變量不存在

<?php 
    $animal = "cat"; 
?> 

和文件b.php,在這裏我想在一個函數

<?php 
    include_once 'a.php'; 

    function section() 
    { 
    $html = "<b>" . $animal "</b>"; 
    return $html; 
    } 
?> 

和文件c.php使用這個變量,其中我使用我的功能section()

<?php 
    require_once 'b.php'; 
    echo section(); 
?> 

我有一個錯誤信息,即variable $animal does not exist in file b.php。爲什麼和我能在這裏做什麼?

最好的問候, 達格納

+0

你曲解的錯誤。 –

+1

變量作用域,$ animal是全局變量,不在section()的範圍內。 –

+0

您能發佈確切的錯誤消息嗎? –

回答

3

發送$animal;的功能:

function section($animal) 
    { 
    $html = "<b>" . $animal "</b>"; 
    return $html; 
    } 
+6

一般來說,如果你必須使用'global',你就錯了。 –

+0

非常感謝! – cadi2108

8

變量有功能範圍。您沒有在函數中聲明變量$animal,因此它在section函數中不可用。

將它傳遞到功能,使那裏提供價值:

function section($animal) { 
    $html = "<b>" . $animal "</b>"; 
    return $html; 
} 

require_once 'a.php'; 
require_once 'b.php'; 
echo section($animal); 
+1

+1不使用全局。 –

+1

爲什麼這不是公認的答案?迄今爲止最安全/最明智的方法。 – comfortablejohn

+0

我認爲這不是被接受的答案,因爲它不會像字面上的技術問題那樣回答,而是最好的答案,並且表明瞭解決這個問題的方法以及許多類似的問題。 –

1
include_once 'a.php'; 

應該

include_once 'variable.php'; 
+0

哇,甚至沒有注意到,+1,儘管他們仍然需要解決範圍問題。 –

1

還有一個選擇是使用類,像:

class vars{ 
    public static $sAnimal = 'cat'; 
} 

然後在您的功能,使用該變量有:

public function section() 
{ 
    return "<B>".vars::$sAnimal."</b>"; 
} 
0

如果它意味着是一個常數,你可以使用PHP的define功能。

a.php只會:

<?php 
    define("ANIMAL", "cat"); 
?> 

b.php:

<?php 
    include_once 'a.php'; 
    function section() { 
     $html = "<b>" . ANIMAL . "</b>"; 
     return $html; 
    } 
?>