2011-02-13 49 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' 
相关问题