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