I do not know the end of the code, a way to get only the 'dynamic properties' and exclude the ones defined in the class as $keys
and $values
is to get the return of get_object_vars()
and execute a unset()
on the keys desired.
class Object{
private $keys = [];
private $values = [];
public function criarArray(){
$obj=get_object_vars($this);
//Código adicionado:
unset($obj['keys']);
unset($obj['values']);
foreach($obj as $key => $value):
$this->keys[] = $key;
endforeach;
return $this->keys;
}
}
$var = new Object();
$var->descricao = "valor para coluna 1";
$var->preco = 22.1;
$var->data = date("Y-m-d");
Output:
array (size=3)
0 => string 'descricao' (length=9)
1 => string 'preco' (length=5)
2 => string 'data' (length=4)
If you want to mount a more incremental version you can take the properties defined in the body of the class and add in a new one ( privateFields
) this must be done in the constructor. Then you can make the difference between the array keys of privateFields
and the dynamic properties. array_push
combined with ...
replace foreach.
class Object{
private $keys = [];
private $values = [];
private $privateFields = [];
public function __construct(){
$this->privateFields = get_object_vars($this);
}
public function criarArray(){
$obj = array_diff_key(get_object_vars($this), $this->privateFields);
array_push($this->keys, ...array_keys($obj));
return $this->keys;
}
}
$var = new Object();
$var->descricao = "valor para coluna 1";
$var->preco = 22.1;
$var->data = date("Y-m-d");
var_dump($var->criarArray());
$var->nova = 'outro valor';
$var->nome = 'fulano';
var_dump($var->criarArray());
Saida:
array (size=8)
0 => string 'descricao' (length=9)
1 => string 'preco' (length=5)
2 => string 'data' (length=4)
3 => string 'descricao' (length=9)
4 => string 'preco' (length=5)
5 => string 'data' (length=4)
6 => string 'nova' (length=4)
7 => string 'nome' (length=4)