P
P
polak2282021-02-27 06:48:23
PHP
polak228, 2021-02-27 06:48:23

How to call a public method in php through object literals?

class A {
  public function a() {
    echo "a";
  }
}

class B extends A {
  public function controll($method) {
    $methods = [
      "returnA" => $this -> a()
    ]; return $methods[$method];
  }
}

$b = new B;
$b -> controll("returnA");


So the question is:
This will only work if there is only one method in $methods, if there are more, then they are called immediately after the array is initialized. How to make it so that you can call them only when necessary, without using switch and conditional statements.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shamanov, 2021-02-27
@SilenceOfWinter

you can use __invoke()

public function __invoke($method)
{
     $methods = get_class_methods(static::class);
      if (!in_array($method, $methods)) {
            throw new BadMethodCallException($method);
      }
      return [$this, $method]();
}

well and use: $instance = new Test(); $instance($method);

T
Tim, 2021-02-27
@Tim-A-2020

If I understand you correctly, you can do something like this

<?php
class A
{
    public function a()
    {
        echo "a";
    }
}

class B extends A
{
    public function controll($method)
    {
        if (method_exists($this, $method)) { // проверяем существует ли метод
            $reflectionMethod  = new ReflectionMethod($this, $method);
            if ($reflectionMethod->isPublic()) { // проверка является ли метод публичным
                return $this->$method(); // вызываем функцию
            }
        }
    }
}

$b = new B;
$b->controll("a");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question