PHP基础知识:无法处理类中的范围

时间:2012-03-05 13:45:49

标签: php

我在OOP中理解范围时遇到了一些麻烦。我想要的是$ foo-> test_item()打印“teststring”......现在它失败了:

  

警告:缺少参数1,用于测试:: test_item()

非常感谢!

<?php

class testing {
    public $vari = "teststring";
    function test_item($vari){ //$this->vari doesn't work either
        print $vari;
    }
}

$foo = new testing();
$foo->test_item();

?> 

4 个答案:

答案 0 :(得分:4)

test_item()应该是:

function test_item() {
    print $this->vari;
}

无需将$vari作为参数传递。

答案 1 :(得分:2)

嗯,你已经声明了一个期望参数缺失的方法。你应该这样做:

$foo->test_item("Something");

至于$this->,它在类方法中。

function test_item(){
    print $this->vari;
}

答案 2 :(得分:1)

函数参数不能为“$ this-&gt; var”,

改变你的课程

class testing {
    public $vari = "teststring";
    function test_item(){ //$this->vari doesn't work either
        print $this->vari;
    }
}

$foo = new testing();
$foo->test_item();

阅读此Object-Oriented PHP for Beginners

答案 3 :(得分:0)

正在发生的事情是$ foo-&gt; test_item()期待作为参数传递的内容,例如

$foo->test_item("Hello");

在这种情况下是正确的。这将打印Hello

但是,您可能想知道它为什么不打印teststring。这是因为通过调用

print $vari;

您只打印已传递给$ foo-&gt; test_item()的变量

但是,如果你做了

function test_item(){  //notice I've removed the argument passed to test_item here...
  print $this->vari;
}

您将打印类property $ vari的值。使用$ this-&gt; ...来调用类范围内的函数或变量。如果你试试没有$ this-&gt;那么PHP将在函数的 local 范围

中查找该变量
相关问题