Question

i'm just making experience on some PHP functions to control some form fields.

I just built a real tiny form to see how can work an OOP form, but i'm experiencing a strange behaviour of strlen command.

Here is the code:

class form and its tiny control

class Form {

public $nome = '';

public function __construct() {
    if(isset($_POST['nome'])){
    $this->nome = $_POST['nome'];
    }
}
public function body() {

    return "<form action=$_SERVER[PHP_SELF] method=post>
           <input type=text name=nome value=\"$this->nome\">
           <input type=submit value=INVIA><br>";
    }

  }

class check {

public $nome;

public function __construct() {
    $this->nome = $_POST['nome'];
}

public function controllo() {

    if ( !empty($this->nome) && strlen($this->nome >= 3) ) {
        echo "$this->nome è un nome valido";
        return TRUE;
    } else {
        return FALSE;
    }
}

}

PHP implementation

<?php
    require '/classes/class.form';

    if(!isset($_POST['nome'])) {
     $form=new Form();
    echo $form->body();   
    } else {
        $check = new check();
        if (!$check->controllo()) {
            $form2=new Form();
            echo $form2->body();
            echo "c'è un errore nei controlli";

        } else {
            echo "tutto ok!";
        }

    }

    ?>

As you see, the check should control if the input text lenght is >=3. If false, the form print out again with the content and with an advise that something is wrong, else it says it's correct.

It happens that if I try with "1" and "2", the control does not make it pass, but when i try with "3", it seems that the script does not match the lenght of the input but its type and it gives me a correct match even if the lenght is a single char.

Moreover, if i try a single alphabetical or a number >3 of alphabetical chars, the control is always false. What can be the problem here?

Était-ce utile?

La solution

You have misplaced your closing parenthesis. strlen should be applied to just the variable $this->nome, not to your boolean expression $this->nome >= 3.

Your original code: if (!empty($this->nome) && strlen($this->nome >= 3)) {

What you intended: if ( !empty($this->nome) && strlen($this->nome) >= 3 ) {

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top