Creating string in PHP

4

Is it possible to create in PHP a variable of type string that contains so many bytes , that is, defined by the programmer?

Example in C:

char string[20];

In this case, string will always have 20 bytes, regardless of what is stored in it.

Resolution with str_pad (args):

$str = str_pad("HelloWorld", 20, "
char string[20];
");

This line guarantees that $str has 20 bytes, that is, if HelloWorld does not have 20 bytes, it fills with \ 0 the remainder.

    
asked by anonymous 29.07.2015 / 14:34

2 answers

5

If you just want to ensure the size you create and use a function that does this whenever you want to ensure 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 in addition to saving a string , save the fixed size of it and apply the above criteria. Something like that (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;
    }
}

Usage:

$texto = new FixedString("teste", 20);

Obviously you need to do better checks, have more methods that will help the job. Making a new type should be very well thought out. I would not do the filling and cutting of the string automatically so, there are better ways to handle this, but the question does not go into detail.

    
29.07.2015 / 14:55
3

PHP is a weak typing language. It is not possible to set an initial size for string - at least not natively.

What you can do are functions or classes that will do this work.

Example:

function fixed_string($string, $length) {
    return substr(sprintf("%' {$length}s", $string), 0, $length);
}

var_dump(fixed_string('oi ', 20));

var_dump(fixed_string('oi oi oi oi oi oi oi oi oi', 20));

Result:

string '                 oi ' (length=20)

string 'oi oi oi oi oi oi oi' (length=20)

Update

I've created an improved class based on the @bigown response.

See that it implements ArrayAccess and some features for encoding identification:

FixedString in GITHUB

Example:

$string = new FixedString('Oi', 2, 'utf-8');
    
29.07.2015 / 15:03