I don’t know the end of the code, a way to take only the 'dynamic properties' and delete the ones defined in the class as $keys
and $values
is to take the return of get_object_vars()
and execute a unset()
on the desired keys.
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");
Exit:
array (size=3)
0 => string 'descricao' (length=9)
1 => string 'preco' (length=5)
2 => string 'data' (length=4)
If you want to build a more enhanced version you can take the properties defined in the class body and add in a new one (privateFields
) this should be done in the constructor. Then you can make the difference between the keys in the array of privateFields
and the dynamic properties. array_push
combined with ...
replace the 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)
$obj=get_object_vars($this); Here the class attributes are returned, so Keys and values.
– Diego Schmidt
So @Diegoschmidt, how to keep only the values I passed?
– Cleber Martins
Do you want this not to appear or that the variable does not exist? Do you need these variables? Actually you need this, it seems to me that it does not. Do you need a class? I don’t think so.
– Maniero
@bigown. I need class and variables. I don’t want them to appear.
– Cleber Martins
I didn’t understand why you either kill the properties of the class that hold the respective key and value, a dictionary (commonly associative array) solves or just a simple function.
– rray
@rray, I don’t want to 'kill', so I said unset() is not an option. I just want to save generated keys without saving variables!
– Cleber Martins
What is shown there does not need any of this, I find it easier to say which problem you want to solve because it seems that this is not the solution.
– Maniero