0

I am trying to read some php code, but can't understand how the variable $predicate here can be used:

private function getRelatedItems() {
    $predicate = Zotero_Relations::$relatedItemPredicate;

    $relations = $this->getRelations();
    if (empty($relations->$predicate)) {
        return [];
    }

    $relatedItemURIs = is_string($relations->$predicate)
        ? [$relations->$predicate]
        : $relations->$predicate;

    // Pull out object values from related-item relations, turn into items, and pull out keys
    $keys = [];
    foreach ($relatedItemURIs as $relatedItemURI) {
        $item = Zotero_URI::getURIItem($relatedItemURI);
        if ($item) {
            $keys[] = $item->key;
        }
    }
    return $keys;
}

As far as I can see $predicate is assigned a value that is never used. But I guess I am misunderstanding the scope somehow, or?

2 Answers 2

3

The $predicate variable holds the name of an attribute on the $relations object. E.g:

$relations->$predicate

If $predicate is set to foo then PHP sees the line as:

$relations->foo
Sign up to request clarification or add additional context in comments.

Comments

1

The variable is used to access a property in $relations variable.

Here is a simplified usage example of variable property access which should clarify the usage for you:

$property = 'firstName';
$data = (object) array(
    'firstName' => 'Justin',
    'lastName' => 'Case',
);

echo $data->$property; //Rquivalent to $data->firstName, which eEchoes 'Justin'

Additionally, it works for functions, and class methods, too:

class Foo
{
     public function bar()
     {
         echo 'Hello, world!';
     }
}

$foo = new Foo();
$method = 'bar';

$foo->$method(); //Equivalent to $foo->bar(); Displays 'Hello, world!'


$function = 'strlen';

echo $function('Hello, world!'); //Is equivalent to calling strlen('Hello, world!');

It's pretty neat!

3 Comments

Ah, now I see it. Thanks. It looked to me like the name of the property was "$predicate" in "->$predicate". Quite confusing. ;-)
I was definitely dumfounded when I first encountered this syntax, too! PHP is the only language I know in which all variables are preceded by a special char ($), so I really thought it was something! Here is the relevant page from the official docs: php.net/manual/en/language.variables.variable.php
;-) - Thanks, I think I am over it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.