1

Is there a way to count the number of variables in an object?

I have a object that is created dynamically, and I want to add each of the properties to a query to update these properties into the database. The variable $oProperties is an object:

public function update_model ($id, $oProperties)
{
    $SQL = "UPDATE `table` SET ";
    $count = 0;
    foreach($oProperties as $property=>$value)
    {   
        $count++;
        $SQL .= strtolower($property)." = '".$value."'";
        if($count !== $oProperties::count()) {$SQL .= ", ";}
    }
    $SQL .= " WHERE id='".$id."';";
}

I need to know the amount of properties in the object to know when to stop adding the comma to the query.

3
  • which type has $oProperties object? Commented Nov 11, 2015 at 12:54
  • Edited the question, $oProperties is an std object Commented Nov 11, 2015 at 12:55
  • To remove the last comma you can just perform: $SQL = substr($SQL,-1) Commented Nov 11, 2015 at 12:56

2 Answers 2

1

You can use get_object_vars:

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;
}

$test = new foo;
var_dump(get_object_vars($test));

Result:

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}

or if your object has type ArrayObject, you can use count method:

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());

But I think will be better use something like that:

public function update_model ($id, $oProperties)
{
    $SQL = "UPDATE `table` SET ";
    $properties = [];
    foreach($oProperties as $property=>$value)
    {
        $properties[] = strtolower($property)." = '".$value."'";
    }
    $SQL .= implode(', ', $properties);
    $SQL .= " WHERE id='{$id}';";
    return $SQL;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thnx, I used count(object_get_vars($oProperties)) to get the amount of variables. Works like a charm :)
1
$arrayObj = (array)($oProperties);    
print_r(count($arrayObj));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.