-1

I'm having to put together a PHP snippet involving capturing form submission data. I'm trying to do this the "right" way with OOP PHP, and I'm struggling with array usage since my Googling seems to bring up sample code that is either too simple or too complex for what I'm trying to do.

How do I create a class method that adds keys and values to an array?

My code, which does not work currently:

class Connection
{
  private $postItem = array();
  public function addPostItem($key,$value) 
  {
    $postItem[$key] -> $value;
  }
  public function printPostItem() { 
    return $this->postItem;
  }
}

$c1 = new Connection;

$c1->addPostItem('FirstName','John');
$c1->addPostItem('LastName','Doe'); 
$c1->addPostItem('Email','JohnDoe@mail.com');

var_dump($c1->printPostItem()); // shows no array content

If I'm going against other best practices here, please let me know.

  • Step one: [Enable error reporting](http://stackoverflow.com/a/6575502/1438393). – Amal Murali Apr 15 '14 at 22:01
  • 2
    Think about your code. If you're using `$this->postItem` in `printPostItem()`, what makes you think you can use `$postItem` in `addPostItem()`? – George Brighton Apr 15 '14 at 22:03
  • "does not work" is not an error description that helps here. What happens? Nothing? Do you get an error? Does the universe implode? – arkascha Apr 15 '14 at 22:04
  • You really should take a look at phps "ArrayAccess" interface and how to implement it. Consult the excellent documentation for this! _That_ would be the right way to do this. – arkascha Apr 15 '14 at 22:04
  • @AmalMurali How should error reporting help here? – arkascha Apr 15 '14 at 22:07
  • @arkascha PHP issues a notice when you access an undefined variable - in this case `$postItem` inside `addPostItem()`. – George Brighton Apr 15 '14 at 22:08
  • @arkascha: Notices are helpful when debugging. See the difference here: [without error reporting](https://eval.in/137215) - [with error reporting](https://eval.in/137216). – Amal Murali Apr 15 '14 at 22:09
  • 1
    @AmalMurali Intereesting thanks. I did not expect a notice in this case, since this is a declaration of a variable. But indeed you are right. This is one of the annoying things about weakly typed languages like php: you never know what you have and how the compiler reacts to that. :-) – arkascha Apr 15 '14 at 22:12

2 Answers2

2

Change:

$postItem[$key] -> $value;

To:

$this->postItem[$key] = $value;

Also as Amal said turn on error reporting.

Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27
2

Use this:

public function addPostItem($key,$value) 
{
    $this->postItem[$key] = $value;
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150