你好,我正在尝试学习如何使用 symfony,所以我想出了一个想法,制作一个页面,显示每次页面刷新时都会递增的数字。我也不想使用数据库,所以练习并不那么容易。我试图制作一个保存变量并递增它的服务,但由于我对 symfony 的理解很差,它不起作用:( 然后我尝试使用会话,但结果是相同的:(( 我用完了到目前为止我所做的:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Addition\GlobalKeeper;
/**
* Class counterController
* @package App\Controller
* @Route("/")
*/
class counterController extends AbstractController
{
private $Gcounter;
public function __construct()
{
$this->Gcounter = new GlobalKeeper();
}
/**
* @Route("/")
*/
public function Counter (){
$this->Gcounter->startfordummy();
$this->Gcounter->increment();
return $this->render('home\insides.html.twig',
[ 'num' => $this->Gcounter->getCounter()]);
}
}
/////
<?php
namespace App\Addition;
use Symfony\Component\HttpFoundation\Session\Session;
class GlobalKeeper
{
public $session;
public function __constructor(){
$session = new Session();
$session->start();
if(null !==$session->get("test")) $session->set("test",0);
}
public function startfordummy(){
$session = new Session();
$session->start();
if(null !==$session->get("test")) $session->set("test",0);
}
public function getCounter()
{
return $this->session->get("test");
}
public function increment()
{
$this->session->set("test", $session->get("test") + 1);
}
}
此代码还导致Call to a member function set() on null
月关宝盒