Create Class for php chat

0

As the title says, I wanted to know how you can create a Class for a PHP chat that has the following structure.

$mensaje->send
$mensaje->delete

But I do not know how, because you have to create the constructor of the class in the following way

$mensaje = new Message()

the function delete uses a variable of an ID and the function of send needs a variable of a text and when I put a single variable that is what that function needs , the constructor gives me an error because it does not find the other variable of the other function.

    
asked by Esteban Fernández 13.12.2018 в 17:54
source

1 answer

1

Alternative # 1

As you put it, the code would be:

class Message {

    public function send($msg)
    {
        // Lógica para enviar mensaje.
    }

    public function delete($id)
    {
        // Lógica para borrar el mensaje con $id.
    }

}

$mensaje = new Message();
$mensaje->send('¡Hola!');
$mensaje->delete(1000);

Alternative # 2

Now, you may want the id to be generated for each new message sent:

class Message {

    protected $id:
    protected $msg;

    public __construct($msg) {
        $this->msg = $msg;
    }

    public function send()
    {
        // Lógica para enviar mensaje.
        $this->id = uniqid();
    }

    public function delete()
    {
        $id = $this->id;
        // Lógica para borrar el mensaje con $id.
    }

}

$mensaje = new Message('Texto a enviar.');
$mensaje->send();
$mensaje->delete();

I recommend the following reading to reinforce the topic: Instance of classes in PHP .

    
answered by 13.12.2018 / 18:05
source