Instantiating dynamic method

Asked

Viewed 66 times

-1

I have several classes, not to be setting method by method I created a class with all methods instantiated, so only Set the method, I wanted to know if it works.

Instances.class.php

class Instancias {
   public $Header;

   public function GetInstancias () {
      $this->Header = new Header;
   }
}

Header.class.php

class Header {
   public function GetHeader () {
      echo "Header";
   }
}

index php.

require "Instancias.class.php";
require "Header.class.php";
$Instancias = new Instancias;
$Instancias->GetInstancias ();
$this->GetHeader ();
  • 3

    If you don’t want to be instantiative is an indication that you don’t need classes, right?

  • @Cool and indicated to do this way?

  • 2

    I don’t think so, but people are doing every crazy thing in PHP that I don’t know anything else, the crazy turned normal :D

1 answer

0

Hello,

Try using Trait to extend common features to various classes like getter and Setter without having to instantiate them from other classes. Just import the trait file into the class you want to implement and use the "use" operator to enable it;

Your index.php call file is not making much sense.

See the code below:

Test class.php

require_once "GetterAndSetterTrait.php";

class teste
{
    use GetterAndSetterTrait;

    private $atributo;  
}

Trait Getterandsettertrait.php

Trait GetterAndSetterTrait
{
    public function __call($func, $value)
    {
        $attrb = strtolower(substr($func,3));
        $func = strtolower(substr($func,0,3));       

        switch ($func) {
            case 'set':
                $this->$attrb = $value[0];
                break;
            case 'get':
                return $this->$attrb;
                break;
            default:
                throw New \Exception('variável '.$attrb.' não existe!');
                break;
        } 
    }
}

index php.

require_once "teste.php";

$a = New teste();

$a->setAtributo("Atributo Configurado com Sucesso");
echo $a->getAtributo(); //Atributo Configurado com Sucesso

Browser other questions tagged

You are not signed in. Login or sign up in order to post.