Home > Mobile >  Dynamic method name in PHP8
Dynamic method name in PHP8

Time:12-16

In a loop I want a trait to populate the member variables.

Problem:

My IDE tells me:

Array and String Offset access syntax with curly braces is no longer supported.

My code

use CustomTrait;

private function mapUserData($mapping, $userData){

  foreach($mapping as $owerKey => $theirKey) {
       $this->set{$owerKey} = $userData[$theirKey];
  }
}

CodePudding user response:

If you want a dynamic method, you probably want this:

$this->{"set$owerKey"}($userData[$theirKey])

The syntax you're using is for an entirely different purpose:

$foo = 'Hello, World!';
var_dump($foo{0});

Demo

CodePudding user response:

Try =)

<?php 

class Test
{
    use CustomTrait;

    private function mapUserData($mapping, $userData): void
    {
        foreach ($mapping as $owerKey => $theirKey) {
            $methodName = "set{$owerKey}";

            // check method
            if (!\method_exists($this, $methodName)) {
                continue;
            }

            $this->{$methodName}($userData[$theirKey]);
        }
    }
}

  •  Tags:  
  • php
  • Related