3

Can i in some way declare an array value to be a string, int etc. without adding a value to it?

For example:

public $arr = array(string);
2
  • It's a nice idea to insist on strongly typed arrays, but you can't do this with an ordinary array. But I think you could set up a class as an ArrayAccess, and refuse non-string values there, by throwing an exception. Commented Oct 7, 2013 at 12:49
  • If it is an array, its type is an array. Commented Oct 7, 2013 at 12:49

6 Answers 6

5

you can use this as easier you think:

$arr = [];
Sign up to request clarification or add additional context in comments.

Comments

2

Short answer, no. PHP is a weakly typed language and doesn't impose types. Closest thing are type hints, but those won't help you in this case.

Comments

2

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

from http://php.net/manual/en/language.types.type-juggling.php

Comments

1

yes you can

$arr = array();
settype($arr,'string');

PHP settype

4 Comments

that's not even near to what the OP wants
can you please explain me what he want?
In short: he wants to declare a type-safe array, i.e. an array whose elements are all of a specified type. It's not possible with PHP arrays (albeit it's possible to simulate type-safe arrays with classes).
I've never seen this keyword before, interesting. However, it's not what the OP wants - this just recasts a value to a new type, rather than refusing to store values of the wrong type. See my comment under the Q for one approach that will work.
0

You cannot declare an array value to be a string, int etc. without defining that value. The value null (which is the closest you can get to not defining a value) has type null.

Comments

0

it's just thought, maybe incorrect but you can test

public function login()
{
    $this->index();//not done yet
    $arr = array();
    foreach ($arr as $element)
    {
        $element = '';
        // or $element = (string)$element;
    }
}

Maybe better way will be to use object of stdClass instead of array; or array of stdClass objects.

1 Comment

Ended up using stdClass object instead. Thanks for the advise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.