在函数中使用调用中的局部变量

时间:2015-10-03 20:06:24

标签: php

经过9个小时的努力才能做到这一点,我已经转向互联网寻求帮助。我无法在Google搜索中找到任何相关答案。

我目前有一个名为Test的课程。 Test接受一个参数。

<?php
    class test {
        private $varpassed;

        public function getVarpas() {
            return $this->varpassed;
        }

        Public function setVarpas($value) {
            $this->varpassed= $value;
        }

        public function stringGen(){

            $testvar = $this->varpassed;
            echo $testvar;
        }
    }

stringGen函数应该在调用时返回$ varpassed变量。使用setVarpas函数设置$ varpassed的值。但是,当我调用stringGen()方法时,我似乎只得到以下错误:

  

致命错误:当不在file.php第14行的对象上下文中时使用$ this。

指向这一行:

$testvar = $this->varpassed;

有没有其他方法可以将变量传递给stringGen方法?我尝试过使用:

self::$this->varpassed;

这也会引发错误。

4 个答案:

答案 0 :(得分:3)

首先创建一个对象实例(这样你就可以在上下文中使用$ this),例如:

$test = new test();

然后你可以打电话:

$test->setVarpas('Hello World!');

现在你可以打电话:

$test->stringGen();

答案 1 :(得分:2)

你必须做这样的事情

$var = new test();
$var->setVarpas("Hello");
$var->stringGen(); // this will echo Hello
你上课时会使用

$this。在课外,你必须使用类对象。

答案 2 :(得分:2)

1)将此更改为class test()class test

2)首先创建和实例$t1 = new test();

3)调用函数$t1->setVarpas(5);

4)现在您可以调用函数$t1->stringGen();

<强>固定

<?php
class test
{
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}

Public function setVarpas($value) {
$this->varpassed= $value;
}

public function stringGen(){

$testvar = $this->varpassed;
echo $testvar;
}
}

$t1 = new test();
$t1->setVarpas(5);
$t1->stringGen();

<强>输出:

5

答案 3 :(得分:1)

你不应该用括号声明一个类。

使用 class test { 代替 class test(){

相关问题