Search code examples
propel

Insert $i variable in object call in Propel & PHP


I'm currently busy rebuilding our CMS in Propel. I currently have the functions to get several body's from our database but i'm struggling to get a desired one based on a $i variable.

The function is as follows:

for ($i = 0; $i < $item->getColumns(); $i++) {
    if (strlen(strip_tags(stripslashes($item->getBody1()))) > 100) {
        $body = strip_tags(stripslashes(substr(strip_tags($item->getBody$i()), 0, strpos(strip_tags($item->getBody.$i()), ' ', 100)))) . ' ...';
    } else {
        $body = stripslashes($item->getBody.$i());
    }
}

In the function above you the see code $item->getBody1(). I want the function to use the $i variable to get the desired body, so for example if $i = 2, the getBody function should be $item->getBody2().

I've tried to use $item->getBody.$i() but that doesn't work. Is there a way I could create this?

Any help is appreciated!


Solution

  • This is not an issue with Propel, but with PHP.

    Instead of using:

    $item->getBody$i();
    

    Use:

    $getIthBodyMethod = 'getBody' . $i;
    $item->$getIthBodyMethod();
    

    PHP manual on variable methods