简体   繁体   中英

Clean way to check if some of an objects properties are null

I have a struct

class foo{
    public $a;
    public $b;
    public $c;
}

That is being populated by a parsed javascript object sent with AJAX. Before I store the struct in my database I want to validate that some of the keys are not null in case someone bypasses the front end validation. I know I can do

function validate($someFoo)
{
    if (!$someFoo->a) {
        return false;
    }
    if (!$someFoo->b) {
        return false;
    }
    return true;
}

But is there a cleaner way to do this (in reality I am checking ~10 fields so that's 10 if statements).

You can use get_object_vars to get an array of the object properties.

function validate($someFoo) {
    foreach (get_object_vars($someFoo) as $var) {
        if ($var === null) {
            return false;
        }
    }
    return true;
}

This is a very clean way to check for null class fields. I don't see any reason to simplify it even more. Just check each field separately.

Using this technique you can easily add other cases which may cause Foo instances to become invalid- for example perhaps you had some other function createConnection(...) that could invalidate a Foo instance. You could add an error( addError ) and check isValid .

You can expand upon this by adding other collections such as Warnings or Notices and more accessor functions for these.

<?php
class Foo {
    private $a;
    private $b;
    private $c;
    private $errors = array();

    public function __construct($a, $b, $c) {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
        if ($this->a === null) {
            $this->addError("A is null");
        }
        if ($this->b === null) {
            $this->addError("B is null");
        }
        if ($this->c === null) {
            $this->addError("C is null");
        }
    }

    protected function addError($error) {
        $this->errors[] = $error;
    }

    public function isValid() {
        $isValid = count($this->errors) == 0;

        return $isValid;
    }
}

$foo = new Foo("TestA", "TestB", null);
if( $foo->isValid() ) {
    echo "Foo is valid";
}
else {
    echo "Foo is not valid";
}

You can use get_object_vars() to achieve your goal.

class foo {
    public $a;
    public $b;
    public $c;
}

function validate($someFoo)
{
    $classVars = get_object_vars($someFoo);
    foreach($classVars as $cv) {
        if(null === $cv) return false;
    }
    return true;
}

$myFoo = new foo();
var_dump(validate($myFoo));

Above code will return false if at least one of the $myFoo variables is NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM