I've seen this used a lot, especially with SimpleXML.
Is this:
$row->unixtime
simply the same as doing this???
$row[unixtime]
What is this called, why/how should it be used?
Object Oriented Programming with PHP
$row->unixtime
$row is an object. unixtime is a property of that object.
$row[unixtime] // I hope you meant $row['unixtime'];
$row is an (associate) array. unixtime is a key in that array.
Asking 'What Objects are' is a bit vague.
Getting started with OOP is not a trivial task. It takes a good while to learn the syntax and nuances, some more time to understand the advantages, and years(arguably) to actually use it effectively.
No, they're not the same. It's about object oriented programming.
->
indicates accessing an object member. For example:
class Test {
public $foo;
public $blah;
}
$test = new Test;
$test->foo = 'testing';
[]
is an array access operator, used by true arrays. Objects can also use it if they implement the ArrayAccess
interface:
class Test2 implements ArrayAccess {
private $foo = array();
public function offsetGet($index) { return $this->foo[$index]; }
// rest of interface
}
$test2 = new Test2
$test2['foo'] = 'bar';
It's totally different.
The first one, $row->unixtime
means that you are accessing the public variable $unixtime
of the object/instance of class $row
. This is Object Oriented Programming.
Example:
class example{
public $unixtime = 1234567890;
}
$row = new example();
echo $row->unixtime; // echos 1234567890
The second one, is to get the key 'unixtime'
of the array $row
. This is called Associative Array. Example:
$row = array(
'unixtime' => 1234567890
);
echo $row['unixtime']; // echos 1234567890
You can easily convert between objects and arrays by using the (array)
and (object)
casts. Example:
$row = array(
'unixtime' => 1234567890
);
$row = (object)$row;
echo $row->unixtime; // echos 1234567890
Off-topic: I actually missed out the unix epoch time 1234567890 in February.
To make your answer short and sweet...
$row->unixtime
This is an object
$row[unixtime]
This is an array
It's likely another idiom pulled from the C language, which is actually what PHP is written in. Many of PHP's features, syntax, and operators, and even many of PHP's native functions, have their roots in C.