How to create an object and methods in PHP

Asked

Viewed 3,080 times

1

I have the following code:

class Database {
    public function __call($name, $arguments) {
        echo $name;
    }
}

and I can do that:

require_once 'Database.php';
$db = new Database();
$db->usuarios();

I wish I could do that:

$db->usuarios->inserir($obj);

This is possible using the magic method __call()?

  • 1

    Vc means to dynamically create/add methods?

  • @rray, this very thing...

  • your method returns some value? if yes, you can have it return the user object and call the Insert method.

  • 1

    The name of this is interface Fluent. But the magic __call() method is not normally used unless you want to transform a "non-fluent" class into an "Fluent structure".

  • @Brumazzid.B., I was able to do it now... but it looks like $db->usuarios()->Insert(); it can be done without the () in the users() ?

  • being a method I believe not, but if your "users" were a variable, it is possible.

  • @Brumazzid.B. Show.. managed using __get() instead of __call(). Thank you, your comments helped me unlock the thought.

  • php is not my strong suit, but need only call.

  • usuarios-> would have to be a class variable, not better usuarios()-> ? I’ve rarely (ever) seen anyone do it $foo->x->z(), but this is already very common: $foo->x()->z(), Is there any need to want to do the way you wrote?

  • @Guilhermenascimento, the Notorm uses in this style. I have no specific need, just wanted to know how it could be done.

  • @Meuchapeu possible is yes, actually it is even easy, would be using __get and __set, but it’s laborious and the worst that it can be "overwritten" (unless you do a validation on __set) I will try to formulate an example. The call method will only work for functions.

  • @Meuchapeu posted an example, I hope it helps.

Show 7 more comments

2 answers

2


In PHP the __call is used when we call a method or function, something like $baz->foo();, when calling $baz->y->x(); the __call is not fired, because the ->y is an object variable, for this you should read about __get and __set, they are fired when we try to record or read inaccessible data/variables (not declared in class).

Follow an example:

<?php
//Classe da tabela usuarios
class ClasseUsuarios
{
    public function inserir($b)
    {
    }
}

//Classe principal
class Database
{
    private $forceWrite = false;
    private $data = array();

    public function __construct()
    {
            //Libera a gravação de qualquer dado em $this->data
            $this->forceWrite = true;

            //Define a classe ClasseUsuarios para $this->data[usuario]
            $this->usuarios = new ClasseUsuarios();

            //Bloqueia a gravação da variável $this->data[usuario]
            $this->forceWrite = false;
    }

    public function __set($key, $value)
    {
        //Checa se é permitido o valor $this->data[usuarios]
        if ($key !== 'usuarios' || $this->forceWrite) {
            //Grava o valor para variáveis não declaradas na classe
            $this->data[$key] = $value;
        }
    }

    public function __get($key)
    {
        //Lê o valor de variáveis não declaradas na classe
        return isset($this->data[$key]) ? $this->data[$key] : NULL;
    }

    public function __isset($key)
    {
        //Se usar empty ou isset em variáveis não declaras irá verificar se ela existe em `$this->data`
        return isset($this->data[$key]);
    }
}

//Objeto ficticio
$obj = array();

//Chama a classe principal
$foo = new Database();

//Vai chamar o método new ClasseUsuarios()->inserir();
$foo->usuarios->inserir($obj);

$foo->usuarios = NULL; //Se tentar gravar a variavel usuarios nada acontece

/*
 * Vai chamar o método new ClasseUsuarios()->inserir();
 * sem ser afetado pelo `$foo->usuarios = NULL;`
 */
$foo->usuarios->inserir($obj);

Documentation: http://php.net/manual/en/language.oop5.overloading.php

1

In PHP that’s called lambda_style or Anonymous Function, to make the implementation easier create a Auxiliary Class (Dinamicmethod), now just have fun :) and test.

Don’t try it right in class Database, the method __call, was not designed to seek Anonymous Function within attributes and yes of class, so we made the class Dinamicmethod.

<?php

class DinamicMethod {

    public function __construct() {

        #leia sobre create_function http://php.net/manual/en/function.create-function.php
        $this->inserir = create_function('', 'echo "Eu sou Uma funcao anonima";');
        $this->deletar = create_function('', 'echo "Eu sou Uma funcao anonima e deleto";');

    }


    public function __call($metodo, $argumentos) {

        #Checa se o objeto ou a classe tem uma propriedade
        if (property_exists($this, $metodo)) {

            #Verifica se o conteúdo da variável pode ser chamado como função
            if (is_callable($this->$metodo)) {
                #Chama uma dada função de usuário com um array de parâmetros
                return call_user_func_array($this->$metodo, $argumentos);
            }
        }
    }
}


class Database {

    public $usuario;

    public function __construct() {

        #objeto de classe padrão php
        $this->usuario = new DinamicMethod();       

    }




}

$db = new Database();
$db->usuario->deletar();

Browser other questions tagged

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