Does PHP Feature Short Hand Syntax for Objects

Does PHP feature short hand syntax for objects?

For simple objects, you can use the associative array syntax and casting to get an object:

<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"

But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).

PHP array of objects (shorthand)

You can declare your array and then simply cast it to an object, e.g.

$arr = [
(object) [
"a" => 1,
"b" => 2,
"c" => 3,
]
];

Which will give you this:

Array
(
[0] => stdClass Object
(
[a] => 1
[b] => 2
[c] => 3
)

)

Is there a shorthand notation for initialising associative arrays or objects in PHP, like the one introduced to JavaScript with ES2015?

As you did it in JS, you can collect all variables by their names in array and do compact():

$a = 'foo'; $b = 'bar'; $c = 'baz';

$ar=['a','b','c'];
print_r(compact($ar));

Output:

Array
(
[a] => foo
[b] => bar
[c] => baz
)

Or just do compact('a', 'b', 'c'); as well.

Demo

Overview of PHP shorthand

Here are some of the shorthand operators used in PHP.

//If $y > 10, $x will say 'foo', else it'll say 'bar'
$x = ($y > 10) ? 'foo' : 'bar';

//Short way of saying <? print $foo;?>, useful in HTML templates
<?=$foo?>

//Shorthand way of doing the for loop, useful in html templates
for ($x=1; $x < 100; $x++):
//Do something
end for;

//Shorthand way of the foreach loop
foreach ($array as $key=>$value):
//Do something;
endforeach;

//Another way of If/else:
if ($x > 10):
doX();
doY();
doZ();
else:
doA();
doB();
endif;

//You can also do an if statement without any brackets or colons if you only need to
//execute one statement after your if:

if ($x = 100)
doX();
$x = 1000;

// PHP 5.4 introduced an array shorthand

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];

Shorthand new Instance-Method syntax in PHP?

Not that i know of.

But! - You could implement a Singleton Pattern and then call:

ClassName::getInstance()->someMethod();

Or, to cut it short ;)

ClassName::gI()->someMethod();

If someMethod does not refer to $this, you could also simply call it as a static function, though it wasn't defined as one:

ClassName::someMethod();

PHP object literal

As BoltClock mentioned there is no object literal in PHP however you can do this by simply type casting the arrays to objects:

$testArray = array(
(object)array("name" => "John", "hobby" => "hiking"),
(object)array("name" => "Jane", "hobby" => "dancing")
);

echo "Person 1 Name: ".$testArray[0]->name;
echo "Person 2 Hobby: ".$testArray[1]->hobby;

What does the syntax '%s' and '%d' mean as shorthand for calling a variable?

They are format specifiers, meaning a variable of a specified type will be inserted into the output at that position. This syntax works outside of classes as well.

From the documentation:

d - the argument is treated as an integer, and presented as a (signed)
decimal number.

s - the argument is treated as and presented as a string.

See the manual on printf. For a list of format specifiers, see here.

indexed array foreach shorthand

So, you are correct that PHP does not support this "out of the box" (except kinda, see below). The first language I know of that does is Objective-C (well, at least the CoreFoundation library). NSArrays and other sets have methods to (in one line) instruct that a given method should be executed on all members; and even more cool (to me, at least) is the concept of "keypaths" and the support that NSArray and others has for them. An example; lets say you have an array of "people" who each have a parent, who in turn have a "name":

arrayOfNames = [peopleArray valueForKeyPath:"parent.name"];

arrayOfNames is now an array of all the parents' names.

The closest thing PHP has is array_map, which you can use together with anonymous functions to very quickly whip something together.

edit anecdotal as it may be, one should remember that loop structures don't need their curly-braces if there is only one statement to execute; so any fancier solutions need to compete with this:

foreach($players as $p) $p->score += 40;

And I'll mention a deeper solution for those OOP fans out there... If you work with collection objects instead of arrays, the world is your oyster with stuff like this. The simplest concept that comes to mind is php's magic __call() method. How simple to iterate over your members and make that call for your users? For more controll, you can implement a few different strategies for iteration (one for transforms, one for filters, etc. Difference being what gets returned, essentially). So in theory you could create a few different iterator classes, and in your "main" collection class implement a couple methods to get one of them, which will be pre-initialized with the contents:

$players->transform()->addScore(40);

where transform() returns an instance of your "don't return the array" iterator, which uses the __call() technique.

The sky starts to open up at this point, and you can start to build filter iterators which take predicates and return another collection of a subset of the objects, and syntax like this is possible:

// send flyer to all parents with valid email address
$parentsPredicate = new Predicate('email');
$players->filteredByPredicate($parentsPredicate)->each()->email($fyler_email_body);

Can I use the arrow operator on a new instance of an object?

This answer comes directly from this question also asked here on SO.

The feature you have asked for is available from PHP 5.4. Here is the list of new features in PHP 5.4:

http://docs.php.net/manual/en/migration54.new-features.php

And the relevant part from the new features list:

Class member access on instantiation has been added, e.g. (new Foo)->bar().



Related Topics



Leave a reply



Submit