Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

successdav's avatar

How to join string to an object

I really dont know how to title this question, however this is what I am trying to get

    public function getDurationSpent()
    {
// This will return the start date to start counting from 
        $start = $this->getRepaymentCycleStartDate();

// The duration_period will be diffInWeeks or diffInMonths or diffInYears depending on what duration_period holds
        $period = 'diffIn' . $this->category->duration_period;

// here now I need to find the difference in weeks or Months or Years using the carbon method DiffIn, so I thought maybe joining the string from $period will work it out. but it doesn't
        return $start->$period->();

    }
0 likes
2 replies
MohamedTammam's avatar
Level 51

If you want to call dynamic method name

return $start->{$period}();

If you're using PHP >= 8, I would use match statement

return match($this->category->duration_period) {
			'Years' => $start->diffInYears(),
			'Months' => $start->diffInMonths(),
			'Weeks' => $start->diffInMonths(),
};

https://www.php.net/manual/en/control-structures.match.php

1 like

Please or to participate in this conversation.