akinuri akinuri - 5 months ago 7
PHP Question

Get global object (property) name inside a function

I have the following object

$db_items
and I pass the sub-object
$db_items->song
as an argument to a function.

$db_items = (object) [
"song" => (object) [
"valid" => false,
"errors" => [],
"inserted" => false,
],
"album" => (object) [
"valid" => false,
"errors" => [],
"inserted" => false,
],
// ...
];

function log_status($item, $item_name) {
if ($item->inserted) {
echo tr([
td($item_name),
td("<span class=\"icon-true\">"),
td(),
]);
} else {
echo tr([
td($item_name),
td("<span class=\"icon-false\">"),
td(ul($item->errors)),
]);
}
}

log_status($db_items->song, "Song");
log_status($db_items->album, "Album");


I want to get rid of the
"Song"
argument in
log_status()
. Is there a way to get the object name of
$db_items->song
-which is
song
- inside the
log_status()
function? Something like:

$obj_name = get_obj_name($item); // song, album, or w/e. depends on the passed argument
$item_name = capitalize($obj_name); // Song


I've tried
get_class($db_items->song)
but it returns
stdClass
, not
song
.

Answer

If you don't want to repeat "song", you could make the function take the whole object as the argument, pass song as a separate argument, and have it get the property value dynamically.

function log_status($items, $field) {
    $item = $items->$field;
    $item_name = ucfirst($field);
    if ($item->inserted) {
        echo tr([
            td($item_name),
            td("<span class=\"icon-true\">"),
            td(),
        ]);
    } else {
        echo tr([
            td($item_name),
            td("<span class=\"icon-false\">"),
            td(ul($item->errors)),
        ]);
    }
}

log_status($db_items, "song");
log_status($db_items, "album");
Comments