0
    /**
     * @return string
     */
    public function getCityIdEncryptedAttribute(): string
    {
        return encrypt($this->city_id);
    }

I want to generate this method dynamically in the class. not in the object.

function __construct ($field)
{
     $methodName = $this->_generateMethodName($field);
     $this->{$methodName} = function () use ($field) {
        return encrypt($this->$field);
     };
}

/**
 * @param string $string
 * @return string
 */
private function _generateMethodName(string $string): string//abc_id
{
    $string = str_replace('_', ' ', $string); //abc id
    $string = ucwords($string);//Abd Id
    $string = str_replace(' ', '', $string);//AbcId
    return "get{$string}EncryptedAttribute";
}

This approach is giving me getCityIdEncryptedAttribute() method to the object, not to the class.

  • The short answer is that you don’t. Instead, if you want a class with dynamic methods look into the [“magic methods”](https://www.php.net/manual/en/language.oop5.magic.php), specifically `__call` – Chris Haas Dec 12 '22 at 04:50
  • Thank you very much @ChrisHaas. That magic method (`__call`) has just fulfilled my purpose. Didn't think of it before. – Mohammad Ali Dec 13 '22 at 04:27

0 Answers0