I haven't been writing php for years but now I'm back. It's good to see new features and more strict typing. I'm using php 7.4 and I'm having a weird issue. I have a model that represents the data in a database table (column names and property names match). I'm creating an insert sql statement from the class definition, meaning it is inserting all of the properties (with the exception of the primary key 'Id'). Then the whole model is passed to the PDOStatement execute command.
Let's say the table is Customer and the class is CustomerEntity:
class CustomerEntity
{
public int $Id;
public string $Name;
public ?string $Email;
public bool $Active;
}
This translates into the following SQL insert:
INSERT INTO Customer (Name,Email,Active) VALUES (:Name,:Email,:Active)
The entity is then converted into an array and passed to the execute.
$statement = $this->Connection->prepare($command);
return $statement->execute($params);
This works fine when all the properties are set. But when something is not set, there's an error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
It comes down to when you do a var_dump like this:
$entity = new CustomerEntity();
$entity->Name = "John";
var_dump($entity);
It gives you this:
object(CustomerEntity)
public 'Name' => string 'John' (length=4)
So the properties that are not defined on the class, disappear. Coming from the world of other strongly typed languages, like C#, this is very odd. I expected them to be there as undefined and in my case, they would be inserted as null into the database (without making the properties nullable and setting them null). It's kinda funny that it says the object is CustomerEntity, even tho it doesn't have all the properties.
Is this really how php works, or can I somehow configure this otherwise? Couldn't find a solution oline.