Learning OOP - Setting an array as a property and adding elements within the class

Hello,

I’m trying to get into OOP and I’m putting together a class to create and validate form inputs/selects/textarea etc.

The property I want to create is an array to hold errors. When a validation method fails to validate the posted input it will add an element to the array which is picked up by the method to create the input then add a class and an error message.

What I’m stuck on is how to create a property as an array, and how to add elements to that array from within the class. Can anyone point me in the right direction?

Maybe I should have started with “hello world”…

Cheers,

Jon

You do not need to create the property “as an array”, PHP does not require you to define the types of variables in advance. You can initialize it to an empty array if you want, but you don’t have to.

Other than being attached to an object, it’s the same as working with an array anywhere else.

$obj = new Example();
$obj->errors[] = 'This is an error message added as an element to the array $obj->errors';

Or with a method:

class Example {

  private $errors = array();

  public function addError($msg) {
    $this->errors[] = $msg;
  }

}

$obj = new Example();
$obj->addError('This is an error message');

Thanks for that, I’m sure I’ll be pestering with more questions shortly…

Cheers,

Jon