Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joe Bruno
35,909 PointsPHP Quick If Exists Add As Object Property
Hello,
Within an object constructor, I need to do roughly 25 statements similar to this:
$tax = $meta['is_tax'][0];
if ($tax) {
$this->tax = $tax;
}
What is a more efficient way of doing this?
I tried to write my own function. It just needs a dynamic name ( in this case 'tax' to go everywhere 'tax' is stated in the expression) and a location ($meta['is_tax'][0]), but I couldn't figure out how to dynamically change the variable name (not the variable value- but this too) itself (so I can state $this->tax and access the value of the 'tax' property within the object later).
Thanks!
2 Answers
thomascawthorn
22,986 PointsHere's what I do If I'm setting loads of array values to an object:
<?php
function __construct($arrayThings) {
foreach($arrayThings as $key => $arrayThing) {
if ($arrayThing) {
$this->$key = $arrayThing;
}
}
}
If you're looking to set things manually and some automatically, you can add a property:
<?php
private $automaticAttributes = array('keyOne', 'keyTwo', 'keyThree');
function __construct($arrayThings) {
foreach($arrayThings as $key => $arrayThing) {
if ($arrayThing && in_array($key, $this->automaticAttributes)) {
$this->$key = $arrayThing;
}
}
}
If there's any special logic you need to do, you can follow it up with custom functions.
If you want to, you can find out more about variable variables (double dollar) here.
Joe Bruno
35,909 PointsRight. Btw why is my syntax not highlighting? I have "three back ticks php" before my first line and "three back ticks" after my last line of code?
thomascawthorn
22,986 PointsCheckout the "Markdown" button above the "post comment" or "post answer" button.
I edited your code - you had three apostrophes '''. What you need are three backticks which look like this `. If you're on a mac, these are next to the shift key on the left hand side.
Joe Bruno
35,909 PointsJoe Bruno
35,909 PointsTom,
Here is the full code. I am already passing an id into the constructor that is a WordPress post id and then creating an object from the post data and meta data.
thomascawthorn
22,986 Pointsthomascawthorn
22,986 PointsAh okay. So you want to only set the array if it exists and then properties if they exist too? I updated my original answer if that helps.