0

I want to create an array within an object (handler) that holds a series of objects (subject) in PHP. The array is a property of the handler and I have a method to create new subjects.

class MyHandler (
  $TheList = array();
  $TempSubject = object; // class subject

  public function AddNewSubject($information) {
    $TempSubject = new subject($information);
    $This->TheList [] = $TempSubject;
  }
)

If I create a new subject as above, does the information persist object persist within MyHandler or is it lost after AddNewSubject ends? I am new to PHP so please comment on any errors.

4 Answers 4

6

It will persist, but you have a typo $This .. should be $this

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

1 Comment

Oh Boy! search and replace! :)
1

to answer your question yes the object will persist in the class

class MyHandler (
     public $TheList = array();

     public function AddNewSubject($information) {
          $this->TheList[] = new subject($information);
     }
)

Comments

0

$TempSubject within the object's method is only a temporary variable. If, however, you were to define your function like this:

public function AddNewSubject($information) {
  $this->TempSubject = new subject($information);
  $this->TheList [] = $this->TempSubject;
}

then the object's property ($this->TempSubject) would be updated each time but a copy of that object would be stored in $this->TheList.

Finally, if you were to define your function like this:

public function AddNewSubject($information) {
  $this->TempSubject = new subject($information);
  $this->TheList [] =& $this->TempSubject;
}

you would find that $this->TheList would contain a list of references to the same object, which would be overridden every time you call the function.

I hope that helps.

Comments

0

You should use the array_push method, check it here: http://php.net/manual/en/function.array-push.php

3 Comments

Why? $array[] = "new value"; does the same thing
@xil3 $array[] is an alias of array_push($array, ??) so yes, it's the same thing. It's really all about author preferences.
@Truth I know what it is, but my point is that this answer didn't add any value to this question.

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.