尝试从命名空间“App \ Bundle \ Controller”调用函数“getAge”

时间:2016-03-23 15:01:17

标签: php symfony

我正在尝试在我的控制器中实例化一个域对象,但我收到此错误“Attempted to call function "getAge" from namespace "App\Bundle\Controller"”。 这是我的结构文件夹:

enter image description here

这是我的Cow.php:

<?php

namespace Domain;

class Cow {
    private $age;

    public function __constructor($ag) {
        $this.$age = $age;
    }

    public function getAge() {
        return $this.$age;
    }
}

我的控制器:

<?php

namespace App\Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Domain;

class CowController extends Controller
{
    public function insertAction()
    {
        $cow = new Domain\Cow(10);
        $age = $cow.getAge();

        return $this->render('AppBundle:cow:insert.html.twig');
    }
}

我已经尝试过命名空间的所有组合:

use Domain;
$cow = new Domain\Cow(10)

use \Domain
$cow = new \Domain\Cow(10)

use \Domain
$cow = new Domain\Cow(10)

我该如何工作?

2 个答案:

答案 0 :(得分:1)

请尝试以下替换:

<?php

namespace Domain;

class Cow {
    private $age;

    public function __construct($age) {
        $this->age = $age;
    }

    public function getAge() {
        return $this->age;
    }
}

控制器:

<?php

namespace App\Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Domain\Cow;

class CowController extends Controller
{
    public function insertAction()
    {
        $cow = new Cow(10);
        $age = $cow->getAge();

        return $this->render('AppBundle:cow:insert.html.twig');
    }
}

基本上,PHP的方法/属性访问符号是->而不是.。此外,为了在名称空间中使用类,您需要使用Domain\Cow而不是\Domain

来指示整个课程的路线。

答案 1 :(得分:1)

首先,我不熟悉那些点缀的呼叫。 但关于你的问题:

试试这个:

use Domain\Cow;

$cow = new Cow(10);