PHP - 变量定义中的错误

时间:2012-07-10 16:27:22

标签: php cakephp

我无法弄清楚以下代码有什么问题:

class ArticlesController extends AppController{
    var $name = 'Articles';
    // Variable $today is defined here so it can be used
    // in other functions in this same class 
    var $today = date('Y-m-d H:i:s',strtotime('now'));
    var $helpers = array('Video');

    function frontpageArticles(){
        $articles = $this->Article->find(
            'all',
            array(
                'conditions' => array(
                    'Article.published' => 1,
                    'Article.publish_date <=' => $today // USED HERE
                )
            )
       )
    );
    return $articles;
    }

    // ...
}

我收到以下错误消息:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in /home/XXXXXXXX/public_html/app/controllers/articles_controller.php on line 10

这是在第10行var $today = date('Y-m-d H:i:s',strtotime('now'));

谢谢,

4 个答案:

答案 0 :(得分:3)

为了进一步详细说明Julien的答案,你不能在类声明中使用变量赋值中的函数,当然,当你定义正常变量时,你可以使用。

解决这个问题的方法是在构造函数中分配值,如下所示:

class ArticlesController extends AppController
{
    public $name = 'Articles';
    // Variable $today is defined here so it can be used
    // in other functions in this same class 
    public $today;
    public $helpers = array('Video');

    public function __construct()
    {
        parent::__construct();

        $this->today = date('Y-m-d H:i:s'); // You also don't need strtotime('now');
    }

    public function frontpageArticles()
    {
        $articles = $this->Article->find(
            'all',
            'conditions' => array(
                'Article.published' => 1,
                'Article.publish_date <=' => $this->today // USED HERE
            )
        );
        return $articles;
    }

    // ...
}

只是旁注,var是PHP4语法,所以如果您使用的是PHP5,我强烈建议您使用访问修饰符,即。 public / private / protected根据字段和方法的使用方式定义字段和方法。

答案 1 :(得分:2)

你不能使用例如。类变量声明中的date()。

答案 2 :(得分:1)

你不能在类属性定义中调用函数,将var定义为:

var $today;

然后在你的函数中设置它:

$today = date('Y-m-d H:i:s',strtotime('now'));

如果你想设置一次 - 创建一个__construct函数

function __construct(){
    $today = date('Y-m-d H:i:s',strtotime('now'));
}

答案 3 :(得分:1)

为什么不使用SQL?我使用CakePHP 2,这就是我的工作方式,工作正常。 另外我认为你错过了一个阵列:

$this->Article->find('all', array(
     'conditions'=>array(
           'Article.published_date<=NOW()'
     )
));