Variable method name

-2

I've had this doubt before but I left it there, now I ask:

Example, I have 1 function:

public function nome_variavel(){
    // A função em si nunca muda, preciso apenas que o nome que ela é definida seja variável.
}

I would like to define this function using a variable name, for example:

$nome_da_funcao = "nome_generico";
public function $nome_da_funcao(){} // Apenas exemplo para entendimento
  

Is this possible? If so, in what form?

    
asked by anonymous 01.11.2015 / 17:38

1 answer

2

I believe this is not possible and even if it were I do not think it would be a very cool practice.

If I understand the your comment , I recommend you maybe create a% associative%, I'll try to formulate an example, I know it's not the format you're using, but it should help.

  

Requires 5.3.0 or higher

app.php

class App
{
     private $views = array();

     public function page($nome, $function)
     {
           if (is_callable($function)) {
               $this->view[$nome] = $function;
           }
     }

     public function exec()
     {
           $page = $_GET['page'];

           if (empty($this->views[$page]) === false) {
                $caller = $this->views[$page];
                $caller();//Executa método
           }
     }
}

index.php

<?php
require_once 'app.php';

$app = new App;
$app->page('nome_generico', function() {
    echo 'Olá mundo';
});
$app->page('sobre', function() {
    echo 'Eu sou Thyago';
});
$app->page('foo', function() {
    echo 'Algo aqui';
});
$app->exec();
  • When you access array this is displayed:

      

    Hello world

  • When you access http://localhost/projeto/?page=nome_generico this is displayed:

      

    I am Thyago

  • When you access http://localhost/projeto/?page=sobre this is displayed:

      

    Something here

01.11.2015 / 23:02