When using setters/getters on arrays, does your set() override the entire array or just the key? What is the accepted or best practice for this?
If you're looking for arrays with add or set, there is an interface in PHP that is called ArrayAccess (The ArrayAccess interface) which allows you to treat an object like an array.
Using it is the accepted way of how to and the only and therefore best practice if you need an object that behaves like an array in PHP.
Not saying you should implement it, but we can take a look at it as one example in hinsight of your questions, it covers every single method required for array access ([…]):
interface ArrayAccess {
public offsetExists(mixed $offset): bool
public offsetGet(mixed $offset): mixed
public offsetSet(mixed $offset, mixed $value): void
public offsetUnset(mixed $offset): void
}
We can see that what you have as $key is named $offset and instead of string or string|int we can see mixed.
Furthermore we can see, that the operation is always per offset, so by key so to say, and never the full array.
If you like to play with that, you can also find a ready made ArrayObject (The ArrayObject class) that implments ArrayAccess, so you can try it out and explore how that approach "feels".
PHP ArrayAccess Example -- https://3v4l.org/mNc9H
<?php
$myArray = new class ([]) extends ArrayObject {
/* implement from ArrayAccess to explore further */
};
// ArrayAccess allows to treat an object as an array
var_dump(isset($myArray['key'])); // bool(false) -- offsetExists()
$myArray['key'] = 'value'; // -- offsetSet()
var_dump($myArray['key']); // string(5) "value" -- offsetGet()
var_dump(isset($myArray['key'])); // bool(true) -- offsetExists()
unset($myArray['key']); // -- offsetUnset()
var_dump(isset($myArray['key'])); // bool(false) -- offsetExists()
The ArrayObject itself does offer a method to set the whole array, it is called exchangeArray().
As we were able to show, there is not one answer to your question when you ask others. Accepted is both, practice makes perfect.
If you're interested, here are some other PHP interfaces that might interest you:
(from: PHP Manual: Predefined Interfaces and Classes and Other Basic Extensions)