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

PHP

PHP 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

Here'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.

Tom,

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.

public function __construct($id)
    {
        //POST DATA
        $data             = get_post($id);
        $meta             = get_post_meta($id);

        if ($data) {

            $this->post_id    = $id;
            $this->title      = $data->post_title;
            $this->content    = $data->post_content;
            $this->post_type  = $data->post_type;
            $this->date       = $data->post_date;
            $this->except     = $data->post_excerpt;
            $this->image_url  = wp_get_attachment_url(get_post_thumbnail_id($id)); //Fix. Separate request.
        }

        if ($meta) { 
            //POST META DATA
            $this->post_meta  = $meta;
            $this->tax        = $meta['is_tax'][0];
            $this->ship       = $meta['is_ship'][0];
            $this->type       = $meta['is_type'][0];
            $this->price      = $meta['the_price'][0];

            $this->author     = $meta['the_author'][0];
            $this->store      = $meta['the_store'][0];

            //USER DATA
            $customer         = new Customer();
            $this->user_id    = $customer->id;
            $user_meta        = $customer->cart_data;

            $this->user_meta  = $user_meta;
            $this->status     = $user_meta[$id]['status'];
            $quantity         = $user_meta[$id]['quantity'];

            if ($quantity) {

                $this->quantity = $quantity;

            } else {

                $this->quantity = 0;

            }

            $this->amount     = $user_meta[$id]['amount'];
            $this->interval   = $user_meta[$id]['interval'];
            $this->int_count  = $user_meta[$id]['count'];
        }
    }

Ah 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.

Right. 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?

Checkout 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.