【问题标题】:Cannot access property from another class无法访问其他类的属性
【发布时间】:2017-08-01 11:02:11
【问题描述】:

这是代码(不包括命名空间、路由):

class OneController extends Controller{
    public $variable = "whatever";
    public function changeVariableAction(){
        $this->variable = "whenever";
        //  any code...
    $this->redirectToRoute("class_two_route_name");
    }

}

use AppBundle\Controller\OneController;
class Two{
    public function otherFunctionAction(){
    $reference = new One();
    return new Response($reference->variable);
    }
}

为什么我看到的是“whatever”而不是“whenever”?我知道执行changeVariableAction()的代码中没有一行,但是当sb进入class One中与此操作匹配的路由时正在执行它???

编辑:

当我在 SF3 之外编写方案时,我很好。

class One{
    public $variable = "whatever";
    public function changeVariable(){
        $this->variable = "whenever";
    }  
}
class Two{
    public function otherFunction(){
        $reference = new One();
        $reference->changeVariable();
        echo $reference->variable;
    }   
}
   $reference2 = new Two();
   $reference2->otherFunction();

【问题讨论】:

  • 您创建了一个One新实例。任何新实例都将$variable 设置为whatever。你的代码是这样写的。

标签: php symfony


【解决方案1】:

因为这条线,您看到的是“Whatever”而不是“Whenever”:

new One();

通过调用“new One();”您正在创建“OneController”类的新实例,因此它将设置其默认值“whatever”,因为在新实例 $reference 中未调用函数“changeVariableAction”。

【讨论】:

  • 是的,我知道那个,但是进入路由匹配类一时不是执行的动作吗?如果没有,那么我可以在第二类中执行它吗?
  • 路由匹配时执行。问题是,当您在类 2 中创建一个新实例时,您实际上是在尚未调用函数的类 1 的新环境中工作。您可以将要设置的值传递给第二类,并在那里进一步使用它。或者在你从第二类调用的第一类中创建一个“更新”函数并在那里更新它。
【解决方案2】:

经过研究,我可以看到在 SF(因为它是一个框架)中,我们不会将 Action 函数视为典型函数(它是关于 http 等的),因此我们无法在另一个类中执行它们。更重要的是,Action 函数内部的整个代码不会影响 Action 函数外部的代码。获取新属性值的唯一方法是通过 url 中的参数发送它们(我认为我们不希望这样)或发送到 db 并从另一个类的数据库中检索它。

这是证据:

class FirstController extends Controller{
    public $variable = "whatever";
    /**
     * @Route("/page")
     */
    public function firstAction(){
        $this->variable = "whenever";
        return $this->redirectToRoute("path");
    }
}

class SecondController{
    /**
     * @Route("/page/page2", name = "path")
     */
    public function secondAction(){
        $reference = new FirstController();
        $reference->firstAction();
        return new Response($reference->variable);    
    }
}

此代码给出错误:调用 null 时的成员函数 get()。

当我删除$reference->firstAction(); 行时,没有错误,并且显示“whatever”(原来如此)。

【讨论】:

    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2018-05-31
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多