Class php mode extends

Asked

Viewed 27 times

1

How could I print on the screen the cpf according to my code?

The code:

<?php

class valida {
    protected $cpf;

    public function cpf($cpf) {
        if(is_numeric($cpf) and $cpf > 11) {
            $this->cpf = $cpf;
            return $cpf;
        }
    }

}
class manda extends valida {
    function foo() {
        return $this->cpf;
    }
}

$cpf1 = $_GET['cpf'];

$p1 = new valida;
$p1->cpf($cpf1);

$sis = new manda;
echo $sis->foo();

What I’m doing wrong ?

1 answer

0


$p1 has nothing to do with $sis, because they are different objects, although they have hierarchy of classes.

If you want the same number on $sis, shall allocate by means of cpf(),

$sis = new manda;
$sis->cpf($cpf1);
echo $sis->foo();

It becomes clearer to understand class hierarchy if we think it serves for code economy in the daughter class,

class manda extends valida {
    public function foo($cpf) {
        // Aproveitando a implementação anterior de cpf().
        $cpf = cpf(100000000000 + $cpf);
        return $cpf;
    }
}

$sis = new valida;
echo $sis->foo($cpf1);

EDIT: Switch cpf() for

public function cpf($cpf) {
    if (is_numeric($cpf) && ceil(log10($cpf)) >= 11) {
        this->$cpf = $cpf + 0;
        return this->$cpf;
    }
}
  • I did it this way: https://ideone.com/wANBeV . It seems that the "Cpf" function is not checking the condition, that is any value/Cpf is being accepted. Could you help me ? Thank you :)

  • I edited the answer.

  • 1

    Lacked a $this-> when calling the method cpf inside foo in the second code. And I wouldn’t particularly recommend treating CPF as numerical, because zeros on the left will be ignored, and if it is necessary to display it, I would have to undergo treatment to fill in the missing zeros. Easier to keep as string and do strlen($cpf).

  • I did it this way and everything went right: https://ideone.com/Ws6Trl . Thank you and hugs.

Browser other questions tagged

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