Undefined variable: position

泄露秘密 提交于 2019-12-11 06:16:59

问题


Sorry guys, I am reading and searching over the web and I cannot find a solution for this :(. If you can please help me :) Thanks.

If I hard code position then it works well. I already tried this on several different ways...

P.S. I have to create some kind of image gallery ajax page for exercise :) I assume this position variable should be in singleton/static class i guess. I was not able to test this class yet, but I think this will work only for first and last image always :) (in java code this would be very easy to do :) ).

Error: Notice: Undefined variable: position in D:\Wamp\www\test\gethint.php on line 11

<?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;
 ?>

回答1:


change this line

return $position++;;

to

return $position++; // extra ;

and access class variable like this

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

for creating static variable use static keyword

private static $position=1;

for accessing static variable use

self::$position;

change this

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

to

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



回答2:


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

You have to get the class variable, not the local variable ;)

And the reset method worked because you would set the local variable to 1 and then return it, in both other methods the $position variable would be undefined.




回答3:


You have this $position++;; in next function for Index class that should be $position++; and to access class property you should use $this.

So use it as $this->position++;



来源:https://stackoverflow.com/questions/15132018/undefined-variable-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!