Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP基础:Can';不要在类中处理范围_Php - Fatal编程技术网

PHP基础:Can';不要在类中处理范围

PHP基础:Can';不要在类中处理范围,php,Php,我很难理解OOP中的作用域。我想要的是$foo->test_item()打印“teststring”…现在它只是失败了: 警告:缺少testing::test_item()的参数1 非常感谢 <?php class testing { public $vari = "teststring"; function test_item($vari){ //$this->vari doesn't work either print $vari; }

我很难理解OOP中的作用域。我想要的是$foo->test_item()打印“teststring”…现在它只是失败了:

警告:缺少testing::test_item()的参数1

非常感谢

<?php

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

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

?> 

函数参数不能为“$this->var”

像这样改变你的班级

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

$foo = new testing();
$foo->test_item();
并阅读此

测试项目()
应为:

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

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

好的,您已经声明了一个方法,该方法需要一个缺少的参数。你应该做:

$foo->test_item("Something");
至于
$this->
,它位于类方法内部

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

这里发生的事情是,$foo->test\u item()期望某个东西作为参数传递,例如

$foo->test_item("Hello");
在这种情况下是正确的。这将打印
Hello

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

print $vari;
您只打印已传递给$foo->test_item()的变量

然而,如果你这样做

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

您将改为打印类
属性
$vari的值。使用$this->。。。调用类范围内的函数或变量。如果您在没有$this->的情况下尝试,那么PHP将在函数的局部范围内查找该变量

@Georgo非常感谢您的回答……我知道这不是很智能。我想用它来测试一些东西。。。