0

好的,所以我有一堂课,每当我调用一两个函数时,它都会跳过它们,为什么会发生这种情况?

这是我的代码:

$name = $this->name("Matt"); //returns "Hello Matt";
$welcome = $this->wel();
echo $name."\n";
echo $welcome;
echo "End.";

function name($name){
return "Hello ".$name;
}
function wel(){
return "Good morning";
}

但它一直跳到' echo "end"; ' 我设置了一个变量,当我再次尝试时它起作用了。但它就像它跳过行然后回到他们那里有什么问题?

4

4 回答 4

0

$this仅在作为对象类成员并在对象上下文中调用的函数中可用。“外部”,$this 将是未定义的,而不是对象。由于您没有提及任何错误/警告,因此您可能已关闭 display_errors 和 error_reporting。您应该打开它们,尤其是在您测试/开发学习时。

于 2012-09-20T20:17:50.313 回答
0

当我将所有代码放入一个类时,它按预期工作:

class Person {
    function __construct() {
        $name = $this->name("Matt"); //returns "Hello Matt";
        $welcome = $this->wel();
        echo $name."\n";
        echo $welcome;
        echo "End.";
    }

    function name($name){
        return "Hello ".$name;
    }
    function wel(){
        return "Good morning";
    }
}


$matt = new Person();

有这个输出:

Hello Matt
Good morningEnd.

但我认为这可能是你想要的更多:

class Person {
    var $name;

    function __construct($name = '') {
        if ($name) $this->name = $name;
    }

    function name(){
        return "Hello " . $this->name;
    }
    function wel(){
        return "Good morning " . $this->name;
    }
}


$person = new Person('Matt');
print $person->name();
print $person->wel();

有这个输出:

Hello MattGood morning Matt
于 2012-09-20T20:22:37.440 回答
0

您需要将您的方法/函数包含在类声明中:

$this仅在班级内可用

<?php

class yourclass{

    function name($name){
        return "Hello ".$name;
    }

    function wel(){
        return "Good morning";
    }


}

$your_object = new yourclass();

$name = $your_object->name("Matt"); //returns "Hello Matt";

$welcome = $your_object->wel();

echo $name."\n";
echo $welcome;
echo "End.";

?>

使用示例$this

<?php
class yourclass{

    function set_name($name){
        $this->name = $name;
        return $this;
    }

    private function welcome(){
        return "Good morning";
    }

    /*example Using $this*/
    function output(){
        echo 'Hello, '.$this->name . PHP_EOL,
              $this->welcome() . PHP_EOL,
             'End.';
    }
}

$your_object = new yourclass();

$your_object->set_name("Matt")->output();
/*
Hello, Matt
Good morning
End.
*/
?>
于 2012-09-20T20:19:41.000 回答
0

除非这只是您的代码片段,否则它不是类的实现。您不需要使用 $this 来调用函数:

$name = name("Matt"); //returns "Hello Matt";
$welcome = wel();
于 2012-09-20T20:20:38.047 回答