0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.