Note that there are some explanatory texts on larger screens.

plurals
  1. PODateTime behaviour when casting to array
    primarykey
    data
    text
    <p>When I try converted DateTime object to be an array, then I dump the variable it will show like below</p> <pre><code>$a = new DateTime('now'); var_dump((array)$a); </code></pre> <p>output</p> <pre> array(3) { ["date"]=> string(19) "2013-12-15 18:24:56" ["timezone_type"]=> int(3) ["timezone"]=> string(12) "Asia/Bangkok" } </pre> <p>from <a href="http://www.php.net/manual/en/language.types.array.php" rel="nofollow">PHP official document</a> explains as below,</p> <blockquote> <p>If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.</p> </blockquote> <p><strong>However</strong>, when see in <a href="http://www.php.net/manual/en/class.datetime.php" rel="nofollow">DateTime manual</a>, it haven't defined this 3 properties at all. Even more than that, if I try to set this 3 properties, it won't return the error, but it also won't have change reflect on the object.</p> <pre> php > $a->date = '2013-12-11'; php > var_dump((array)$a); array(3) { ["date"]=> string(19) "2013-12-15 18:24:56" ["timezone_type"]=> int(3) ["timezone"]=> string(12) "Asia/Bangkok" } </pre> <p><strong>My question is, how to make object be able to casting to be array like this behaviour?</strong></p> <p><strong>[Update]</strong> Even you use <a href="http://www.php.net/manual/en/function.get-object-vars.php" rel="nofollow">get_object_vars</a>, on the document, you will see as following</p> <blockquote> <p>Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.</p> </blockquote> <p>It will show you that if the "date", "timezone_type", "timezone" is public properties, why they are not be able to set.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload