2017-08-01 64 views
-3

下面的代码访问属性(不包括命名空间,路由):无法从另一个类

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); 
    } 
} 

我为什么看到“什么”而不是“每当”?我知道在执行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(); 
+3

您创建一个'***'的***新实例***。任何新的实例都会将'$ variable'设置为'whatever'。你的代码是这样说的。 – deceze

回答

0

您看到 “什么” 而不是 “每当”,因为这行:通过调用

new One(); 

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

+0

是的,我知道的那一个,但不是进入路线匹配一级时执行的动作?如果没有,那么我可以在第二课中执行它吗? – DeveloperKid

+0

它在路由匹配时执行。问题是当你在类2中创建一个新的实例时,你正在有效地工作在一个尚未被调用函数的类One的新环境中。你可以传递你想要设置到第二类的值,并在那里继续使用它。或者在第二课中调用的第一课中创建一个“更新”功能并在那里更新。 – tbrennan

0

经过研究,我可以看到在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);  
    } 
} 

该代码给出了一个错误:调用上的空成员函数get()方法。

当我删除行$reference->firstAction();没有错误和“无论”出现(所以原来的)。