I am using $this in a class, but it keeps giving me Fatal error: Using $this when not in object context [duplicate]
-
26-05-2021 - |
Question
I created a a cart class which contains songs to be bought. The cartSong
class works fine, but when I use the cart class, an error about $this
always comes up. I want the variable $songList (array)
to add a song object to the cart every time addToCart
is called, and $trackno
to iterate. The line where the error is located is specified in the code:
<?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;
}
}
?>
There is only one error when I run this:
Fatal error: Using $this when not in object context in C:\wamp\www\musiquebasse\data\cartfunctions.php on line 40.
Here is where I called the code, this is 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;
}
?>
Solution
You are calling addToCart as a static method using the :: operator in your code:
$cart::addToCart($album, $track);
Instead you should reference the function against the instantiated object, using the -> operator:
$cart->addToCart($album, $track);
You have the same problem with the remove and empty calls as well.
Edit: I see that you already fixed in the comments - I'll just leave this here I guess.