我在一个类中使用$ this,但它一直给我致命的错误:在不在对象上下文中时使用$ this

时间:2012-03-25 02:17:25

标签: php object this fatal-error contextpath

我创建了一个购物车类,其中包含要购买的歌曲。 cartSong类工作正常,但是当我使用购物车类时,总会出现关于$this的错误。我希望变量$songList (array)每次调用addToCart时都会向购物车添加歌曲对象,并$trackno进行迭代。错误所在的行在代码中指定:

<?php
$indexpath = "index.php";
$cartpath = "data/cart.xml";

class cartSong{
    private $albumid = null;
    private $trackno = null;

    function cartSong($albumid, $trackno){
        $this->albumid = $albumid;
        $this->trackno = $trackno;
    }

    function setSong($albumid, $trackno){
        $this->albumid = $albumid;
        $this->trackno = $trackno;
    }

    function getTrackNo(){
        return $this->trackno;
    }

    function getAlbumID(){
        return $this->albumid;
    }
}

class cart{
    public $songList;
    public $songCount;

    function cart(){
        $this->songList = array();
        $this->songCount = 0;
    }

    function addToCart($albumid, $trackno){
        $checker=0; 

        for($i=0;$i<$this->songCount;$i++){ // THIS LINE GIVES AN ERROR ($this->songCount)
            if( ($this->songList[$i]->getAlbumID()==$albumid) && ($this->songList[$i]->getTrackNo()==$trackno) )
                $checker=1;
        }

        if($checker==0){
            $song = new CartSong($albumid, $trackno);
            $this->songList[]=$song;
            $this->songCount++;
        }
        else
            echo "Song already exists in cart.";
        echo $this->songList[0]->getAlbumID();
        echo $this->songList[0]->getTrackNo();
    }

    function removeFromCart($albumid, $trackno){
        $checker=0;

        for($i=0;$i<count($songList);$i++){
            if( ($songList[$i].getAlbumId()==$albumid) && ($songList[$i].getTrackNo()==$trackno) )
                $checker=1;
        }

        if($checker==1){
            array_splice($songList,$i);
        }
        else
            echo "Song does not exist in cart.";
    }

    function emptyCart(){
        $songList = (array) null;
    }
}

?>

运行时只有一个错误:

  

致命错误:在第40行的C:\ wamp \ www \ musiquebasse \ data \ cartfunctions.php中不在对象上下文中时使用$ this。

这是我调用代码的地方,这是addtocart.php:

<?php
$indexpath = "index.php";
require_once "data/SessionControl.php";
require_once "data/cartfunctions.php";

    $album = $_GET["albumid"];
    $track = $_GET["trackno"];
    $action = $_GET["action"];
    $cart = new cart();

    // insert checker here (if the same song is added to cart

    switch($action) {   //decide what to do 
        case "add":
            $cart::addToCart($album, $track);
        break;

        case "remove":
            $cart::removeFromCart($album, $track);          
        break;

        case "empty":
            $cart::emptyCart();
        break;

    }

?>

1 个答案:

答案 0 :(得分:1)

您正在使用代码中的::运算符将addToCart作为静态方法调用:

$cart::addToCart($album, $track);

相反,您应该使用 - &gt;引用针对实例化对象的函数。操作者:

$cart->addToCart($album, $track);

同样的删除和空调用也有同样的问题。

编辑:我看到你已经修改了评论 - 我想把它放在这里我想。