Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can this kind of statement work in PHP?

$user->Phonenumbers[]->phonenumber = '123 123';
$user->Phonenumbers[]->phonenumber = '456 123';
$user->Phonenumbers[]->phonenumber = '123 777';

I've never seen this kind of syntax

EDIT

This seems more probably a feature,do you guys know how can I implement a feature like this?

like image 798
ORM Avatar asked Feb 21 '10 17:02

ORM


People also ask

Why conditional statements are used in PHP?

Conditional statements are used to perform different actions based on different conditions.

What does statement mean in PHP?

A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces.

How does if...else statement work?

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.


2 Answers

It seems that something like the following creates an stdClass object with the property phonenumber and pushes it into the $user->Phonenumbers array:

$user->Phonenumbers[]->phonenumber = 12345;

I’ve never seen that syntax too.

like image 154
Gumbo Avatar answered Sep 28 '22 07:09

Gumbo


Gumbo is right, here is a working example:

<?php
class Test
{
    public $arr = array();
    public $obj = null;
}
$a = new Test();
$a->arr[]->foo = 1234;
$a->arr[]->bar = 'test';
var_dump( $a->arr );

// even more weird on null objects
$a->obj->foobar = 'obj was null!';
var_dump( $a->obj );

returns:

array(2) {
  [0]=>
  object(stdClass)#2 (1) {
    ["foo"]=>
    int(1234)
  }
  [1]=>
  object(stdClass)#3 (1) {
    ["bar"]=>
    string(4) "test"
  }
}
object(stdClass)#4 (1) {
  ["foobar"]=>
  string(13) "obj was null!"
}

edit: Okay, I found something related in the php manual about this:

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. (source)

So using the -> syntax converts the thing into an object. In the example above $obj is null, so a new, empty instance is created, and the foobar member is set.

When looking at the array example, arr[] first creates a new (empty) array element, which is then converted into an empty object because of the -> syntax and the member variable is set.

like image 33
poke Avatar answered Sep 28 '22 09:09

poke