2011-02-13 113 views
0
class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld($helloWorld) 
    { 
     echo $helloWorld; 
    } 

} 

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld(); 

上面給出了這樣的錯誤:爲什麼這個簡單的hello world PHP代碼不起作用?

Warning: Missing argument 1 for saySomething::sayHelloWorld(), called in C:\xampp\htdocs\test.php on line 15 and defined in C:\xampp\htdocs\test.php on line 7 
+0

爲sayHelloWorld() – 2011-02-13 07:05:01

回答

5

因爲你缺少的參數1 saySomething :: sayHelloWorld()。當你定義該函數時,你將它定義爲有1個必需的參數。

定義你的函數是這樣的:

class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld() 
    { 
     echo $this->helloWorld; 
    } 

} 
0
class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld() 
    { 
     echo $this->helloWorld; 
    } 

} 

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld(); 
1

你可能想正確的代碼應該是:

class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld() 
    { 
     echo $this->helloWorld; 
    } 

} 

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld(); 

function sayHelloWorld($helloWorld)你寫的線,你的意思是$helloWorld是一個參數傳入方法/函數。要訪問類變量,請改爲使用$this->variableName

0

,你可以修改它

class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld($helloWorld="default value if no argument") 
    { 
     echo $helloWorld; 
    } 

} 

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld(); 

或helloWorld的已定義您的sayhelloworld不需要爭論。

類saySomething {

var $helloWorld = 'hello world'; 

function sayHelloWorld() 
{ 
    echo $helloWorld; 
} 

}

$ saySomething =新saySomething(); $ saySomething-> sayHelloWorld();

0

使用$ this指針

class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld() 
    { 
     echo $this->helloWorld; 
    } 

} 

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld(); 
1

以上所有答案都是功能正確。

您問「爲什麼」 - 原因是由於編程術語'範圍'。範圍定義了哪些變量是可見的,以及何時可見。您的示例代碼定義了一個類級變量$ helloWorld,並且還定義了一個類參數$ helloWorld。

函數執行時'在作用域'中的唯一變量是作爲參數傳遞的唯一變量。因此,當代碼稍後調用該方法而未向參數分配值時,會嘗試輸出其值(因爲它沒有)。此時該方法不能看到類級變量,因爲它不在範圍內。

的溶液,如上述,是要麼值傳遞給函數的參數,使得其被定義(並且因此不產生誤差)

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld('Hello world... again'); 

這將一個值傳遞給類方法,你會在屏幕上看到'Hello world ... again'。

這可能是,也可能不是,你打算做什麼。如果您希望瞭解如何將類級別變量引入範圍,那麼最常見的方法是使用預定義的PHP變量'$ this',該變量允許該方法引用(即「查看」)其他變量和方法班上。變量'$ this'自動地魔術般地始終指向當前類,無論它在哪裏使用。

class saySomething { 

    var $helloWorld = 'hello world'; 

    function sayHelloWorld($helloWorld) 
    { 
     //set myOutput to parameter value (if set), otherwise value of class var 
     $myOutput = (isset($helloWorld)) ? $helloWorld : $this->helloWorld; 
     echo $myOutput; 
    } 

} 

$saySomething = new saySomething(); 
$saySomething->sayHelloWorld(); // Outputs 'hello world' from class definition 
$saySomething->sayHelloWorld('Hello world... again'); // Outputs 'Hello world... again' 
相關問題