How to resolve error Catchable fatal error while trying to show messages

6

I have a page where I check if the user has filled all the fields of a form but when trying to show the messages to the user script returns me an error, I'm doing this:

class SendEmail
{
   private $nome;
   private $email;
   private $telefone;
   private $cidade;
   private $uf;
   private $assunto;
   private $mensagem;
   private $receive_mail;

   public function __construct($data)
   {

    $this->receive_mail = "[email protected]";
      try
      {
        if (count($data) sendMail();

      } catch (Exception $e) {
            return json_encode(array('success'=>'0','errors'=>$e->getMessage()));
      }    

     }

     public function sendMail()
     {
      $subject = $this->assunto;
      $body = "From {$this->nome}, \n\n{nl2br($this->mensagem)}";
      $headers = 'From: ' . $this->email . "\r\n" .
        'Reply-To: ' . $this->email . "\r\n" .
        'Content-type: text/html; charset=utf-8' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

       if (mail($this->receive_mail, $this->assunto, $body, $headers)) {
          return json_encode(array('success'=>'1','message'=>'Mensagem enviada com sucesso!'));
       } else {
          throw new Exception("Ocorreu um erro no envio da mensagem, por favor, tente mais tarde.");
       }
     }
}

if ($_POST) {
    // Aqui ele retornará um JSON com os erros ou a mensagem de sucesso
    echo json_encode(new SendMail($_POST)); 
}

And the whole message is this:

Catchable fatal error: Object of class SendEmail could not be converted to string in /home/anc/public_html/anc/sendEmail.php on line 84

The problem is that I'm trying to show Objeto as string so I read in the php manual, but I could not solve it.

    
asked by anonymous 04.12.2015 / 12:02

2 answers

5

The problem with the 84 line is print , which tries to convert the object to string before printing it.

Objects in PHP can not be converted to string, unless they implement the magic method __toString .

Example:

class MyClass
{
    protected $minha_informacao = 'Informação importante';

     public function __toString()
     {
          return (string) $this->minha_informacao;
     }
}

You can convert them simply by doing so:

$obj = new MyClass;

echo $obj;

$string = (string) $obj;

If you want to see the values of an object, you should do what is described in the @rray response

I also saw that you want to convert an object to the json format. This in PHP is only possible using the json_encode function.

Note that in classes that do not implement the interface JsonSerializable this serialization to json does not occur in a desired way. The interface forces your class to contain the jsonSerialize method, which will "show" the json_encode function as that object will be serialized.

So do this:

class SendMail implements JsonSerializable
{
   public function jsonSerialize()
   {
       return $this->dados_que_quero_serializar;
   }
}

So it's possible to do:

 echo json_encode(new SendMail($_POST));

If you want to combine the useful and enjoyable for your object to be "printed" without having to change the shape you print, you can combine the two shapes I taught you above:

class SendMail implements JsonSerializable

{
     public function jsonSerialize()
     {
          return array('email' => $this->email, 'nome' => $this->nome);
     }

     public function __toString()
     {
           return (string) json_encode($this);
     }
}

The output of this will be:

echo new SendMail($_POST);

Output:

 {"nome": "Wallace Maxters", "email" : "[email protected]"}
    
04.12.2015 / 12:03
3

To display the structure of an array, object, or other type other than a scalar, use the functions, print_r() or var_dump() .

The class constructor should not return anything other than the object which is already done automatically, it makes no sense to return something else. You call the creation of an object to manipulate and receive a the string. It's the same thing as ordering a pizza at a restaurant and the waiter bringing a salad.

 public function __construct($data){
    $this->receive_mail = "[email protected]";
    try {
        if (count($data) sendMail();

    } catch (Exception $e) {
       //return estranho no construtor
       return json_encode(array('success'=>'0','errors'=>$e->getMessage()));
    }    
}

When calling this line do you expect an email object or a json?

//essa linha retorna um objeto ou json? o que esperar?
$email = new SendMail($_POST);
//a linha a baixo seria o mais adequado.
$json = json_encode($email->getMessage());

Simplified Problem Example:

class Email{
    private $message;

    public function __construct($msg){
        $this->message = $msg;
        return 'WTF? O.o';
    }

    public function getMessage(){
        return $this->getMessage();
    }
}

Example 1

$msg = 'Into the void';
$email = new Email($msg);
var_dump($email);

The output will be:

object(Email)[1]
  private 'message' => string 'Into the void' (length=13)

A return in the constructor is never executed, it only leaves the understanding of the method strange. Have you called / requested to build an email object because it would receive something different?

From php5.4 it is possible to create an object and already invoke a method just by adding parentheses around the new class. The other solution is to create a new variable or call the return of the direct method on a function ex: json_econde() .

Example 2, solution:

$msg = 'Into the void';
echo (new Email($msg))->getMessage();

Or:

$msg = 'Into the void';
$email = new Email($msg);
echo json_encode($email->getMessage());

Output:

Into the void
    
04.12.2015 / 12:06