2

我创建了一个包含要购买的歌曲的购物车类。该类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;

    }

?>
4

1 回答 1

1

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

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

相反,您应该使用 -> 运算符针对实例化对象引用该函数:

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

remove 和 empty 调用也有同样的问题。

编辑:我看到你已经在评论中修复了 - 我想我会把它留在这里。

于 2012-03-25T04:41:33.660 回答