Mohammad Ali
Mohammad Ali

Reputation: 1

How to add class method dynamically through constructor (PHP). N.B: I do not need method in object (ex: $this->$methodName). not like that

    /**
     * @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.

Upvotes: 0

Views: 35

Answers (0)

Related Questions