开发者

PHP: array_push inside a class

开发者 https://www.devze.com 2023-03-21 10:03 出处:网络
Hi Im new to PHP and trying to implement a class. Inside the class one of my variables is an array. Basically, what I am confused about is how do I initialize the array and then add an element to it u

Hi Im new to PHP and trying to implement a class. Inside the class one of my variables is an array. Basically, what I am confused about is how do I initialize the array and then add an element to it using a function. This is the code I have so far but Im getting a syntax error message in the IDE.

<?php
 class Food
 {
  var $foodName = "";
  var $foodCals = "";
  var $foodDesc = "";
  var $foodPrice = "";
  var $numSides = "";
  $sidesArray = array();

  function addSide($sideItem)
  {
    array_push($sidesArray, "$sideItem");
  }

 }
?>

Get a syntax error that says:

Syntax error: unexpected: $sidesArray expected: function, const, var, }, static, abstract, final, private, protected开发者_运维技巧, public

What am I doing wrong? Thanks.


You need to reference your member variable like so in the function:

$this->sidesArray

And in the class declare it like so:

public $sidesArray;

I recommend you read Classes and Objects on php.net.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号