未定义的变量:位置

时间:2013-02-28 09:34:37

标签: php ajax variables undefined

对不起,伙计们,我正在网上阅读和搜索,我无法找到解决方案:(。 如果你能帮助我:)谢谢。

如果我硬编码位置,那么效果很好。我已经用几种不同的方式试过了......

P.S。    我必须创建某种图像库ajax​​页面进行练习:)我认为这个位置变量应该是单例/静态类我猜。我还没能测试这个类,但我认为这只适用于第一个和最后一个图像总是:)(在java代码中这很容易做:))。

错误:  注意:未定义的变量:第11行的D:\ Wamp \ www \ test \ gethint.php中的位置

<?php

class Index {
    private $position=1;

    public function next(){
        return $position++;;
    }

    public function prev(){
        return $position--;
    }

     public function reset(){
        $position=1;
        return $position;
    }
}

$action=$_REQUEST["action"];
    $index = 0;

if($action!=1){
    $index=Index::prev();
} else {
    $index=Index::next();
}

if($index < 1){
    $index=7;
}
if($index > 7){
    $index=1;
}

    $response="<img border=\"0\" src=\"".$index.".jpg\" alt=\"".$index."\" width=\"500\" height=\"334\">";

 echo $response;
 ?>

3 个答案:

答案 0 :(得分:0)

class Index {
    private $position=1;

    public function next(){
        return $this->position++;
    }

    public function prev(){
        return $this->position--;
    }

     public function reset(){
        $this->position=1;
        return $this->position;
    }
}

你必须得到类变量,而不是局部变量;)

并且reset方法有效,因为你将局部变量设置为1然后返回它,在其他两种方法中,$ position变量都是未定义的。

答案 1 :(得分:0)

更改此行

return $position++;;

return $position++; // extra ;

并像这样访问类变量

$this->position++; // not $position

用于创建静态变量使用static关键字

private static $position=1;

用于访问静态变量使用

self::$position;

更改此

if($action!=1){
    $index=Index::prev();
} else {
    $index=Index::next();
}

$in = new Index();
if($action!=1){
    $index= $in->prev();
} else {
    $index= $in->next();
}

答案 2 :(得分:0)

$position++;;类的下一个函数中Index应该是$position++;,并且要访问类属性,你应该使用$ this。

因此请将其用作$this->position++;