If you just want to guarantee the size create and use a function that does this whenever you want to guarantee the size:
function fixedSTring($txt, $length) {
$length = max($length, strlen($length);
return str_pad(substr($txt, 0, $length), $length);
}
If you want something guaranteed and automatic, just create a new type, a new class that besides saving a string, keep her fixed size and apply the above criterion. Something like this (not complete and tested, it’s just a base)
final class FixedString {
private $txt = '';
public function __construct($txt, $length) {
$length = max($length, strlen($length));
$this->txt = str_pad(substr($txt, 0, $length), $length);
}
public function __toString() {
return $this->txt;
}
}
Use:
$texto = new FixedString("teste", 20);
I put in the Github for future reference.
Evidently you need to do better checks, have more methods that help the job. Making a new type should be very well thought out. I would not fill and cut the string automatically like this, you have better ways to deal with it, but the question doesn’t go into detail.
You want a new type or just make the string have a fixed amount of characters?
– Maniero
I want her to have a fixed amount of characters
– Vynstus
In php you don’t have these things in C. It’s direct :
$variavel = 'minha_string'
. As I said in another answer: php is a weak typing language.– Wallace Maxters
No, but you can make a 20-character substr that would be a solution
– Adir Kuhn