Pass function by validation function in php

Asked

Viewed 60 times

0

Good, I have a class "Entity", where I have the property "Phone", for the phone, I have a function the part that validates the phone number "isvalidTelephone", I also have a function that prints all properties... My doubt is of beginner.. How do I do instead of it simply echo the phone number, print the phone number by going through the validation of "isvalid"?

Here is my code:

GETTER AND SETTER:

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

/**
 * @param mixed $telefone
 */
public function setTelefone($telefone) {
    if ($telefone === $this->isvalidTelefone($telefone)) {
        echo "este numero esta errado";
    } else {
        echo "este numero esta certo";
    }
}

VALIDATION FUNCTION:

public function isvalidTelefone($telefone) {
    if ((strlen($telefone) < 9) || (strlen($telefone) > 9)) {
        return FALSE;
    } else {
        return TRUE;
    }
}

FUNCTION THAT PRINTS PROPERTIES:

public function printEntidade() {
    return $this->nome . '<br>' .
            $this->email . '<br>' .
            $this->nif . '<br>' .
            $this->codpostal . '<br>' .
            $this->localidade . '<br>' .
            $this->morada . '<br>' .
            $this->pais . '<br>' .
            $this->telefone . '<br>' .
            $this->saldo;
}

Thank you!

  • Opa Nelson, you want to print the phone number only if it is valid?

  • Hello Andre, yes that’s it, I want you to print if the number is valid, IE, I want the setTelefone has the validation function.

1 answer

1


First valide no setTelefone and only assign the value if the isValidTelefone be it true, see below:

/**
 * @param mixed $telefone
 */
public function setTelefone($telefone)
{
    if($this->isvalidTelefone($telefone))
    {
        $this->telefone = $telefone;
    }
}

After that you can put a ternary in the function printEntidade checking whether the $this->email and concatenating if it exists, see below:

public function printEntidade()
{
    return $this->nome . '<br>' .
        $this->email . '<br>' .
        $this->nif . '<br>' .
        $this->codpostal . '<br>' .
        $this->localidade . '<br>' .
        $this->morada . '<br>' .
        $this->pais . '<br>' .
        (isset($this->telefone) ? $this->telefone . '<br>' : '') .
        $this->saldo;
}
  • 1

    Thank you so much! This is what I was looking for!

  • One more thing... I also have a "setSaldo", where I have the following: public Function setSaldo($balance) { Return '<br>' . '€' . number_format($balance, 2); } ?

  • The set function does not aim to return something, it has the function to set an attribute. Do as follows: public Function setSaldo($balance) { $this->balance= '€' . number_format($balance, 2); }

  • 1

    Very good, thank you very much for your help André, I learned a lot!

Browser other questions tagged

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