php array selector unsure of differnce - php

hi I working with Drupal and it uses arrays to a level I'm not very familier with, I've a quick question which is what is the difference between these 'selectors'(is that the right term)?
This causes an error "Fatal error: Cannot use object of type stdClass as array in..."
$node['field_geoloc']
this works (im using it in an if != null statement)
$node->field_geoloc
hopefully an easy question...
thanks.

Pretty easy.. the error says it all:
"Fatal error: Cannot use object of type stdClass as array in..."
You are attempting to use an object as an array.
Object properties aren't accessibly using the $array['key'] method that you are used to. You need to access properties like:
`$object->property`
If you have an object, you can get the properties from that array by using the get_object_vars method. But I know from experience that you should not use that method with a $node in Drupal.

-> is operator for accessing public object properties (and call public methods). In order for an object properties to be accessed with $object['key'] syntax, it have to implement ArrayAccess. Other option is to cast the object to array ( $node = (array) $node (but this will work only for first-level keys, e.g. it will turn $node->page to $node['page'], but not $node->page->title to $node['page']['title'] - the later will be accessible via $node['page']->title

Because you can't use object as an array.
That first is an array and that second is an object.

The first one is an array, the second one is an object (of class StdClass).
But you may be interested in this interface: http://php.net/manual/en/class.arrayaccess.php which allows accessing an object as an array (so you do $obj['key'] instead of $obj->key)

Related

PHP callback - array or arrow syntax?

Let's assume we have this function
<?php
function run($callback)
{
$callback($some, $params);
}
How to call it?
run($someObject->callback);
or rather
run([$someObject, 'callback']);
The first one seems better to me especially because of code suggestion but in documentation is used array notation.
Why is first one worse than second one?
The array notation is better because the arrow notation doesn't work. Functions in PHP aren't first class objects which can be passed around. Whenever you "pass a function", you must pass it by name; i.e. only its name. To pass an object method, you need to pass the object and the method name using the callable pseudo type notation.

How to get rid of array/object casting in PHP?

Some methods/functions only accept/return arrays, others only get/give objects. In my day to day PHP programming I have to repetitively convert objects to array and vice versa. ((object) ['x'=>3] and (array) (new stdClsss())).
Most classes do not implement ArrayAccess. Smartly in JavaScript, these two syntaxes are interchangeable. Is there any hack, workaround to stick to one of them and get rid of variable casting and "Cannot use object of type xxx as array in " or "Cannot use object of type stdClass as arhray in "Cannot access property on non-object" messages.
I came up with ary.
$var= ary(['x' => 'foo', 'y' => 'bar']);
$foo = $var->x; //or
$foo = $var['x'];
Try using php serializing function, instead of trying to convert them.
$array = array();
$obj = serialize($array);
$again = unserialize($obj);
This will help you if your interchange is about to save datum.
if, working with the object is your bulk task, try to define a class library for your object and then, implement your function like ToArray(), ToString(), ToObject() or ToStorable(), instead of converting them in your code with natural functions.

What is the class of MySQL object?

If we use mysql_fetch_object, it returns recordset as an object.
I want to know that is this object is object of some particular class?
Or simply, returned object by mysql_fetch_object is object of which class?
The documentation itself states, that the resulting class will be stdClass or whatever you pass as the second parameter to the function.

How to find if a perversely constructed object is empty in PHP

I'm working with an object fed back from a class. For some reason, the class spits out an object with numbered properties (0, 1, 2, etc.). I need to check if the object is empty. The standard trick, empty(get_object_vars($obj)), won't work, because get_object_vars returns an empty array even when the object has (numbered) properties.
For reference, the object I'm working with is the one returned by the legislatorsZipCode method of the PHP interface for Sunlight's API. You can see a print_r of a sample response here.
Judging by the code, the author made the mistake of casting a numerically indexed array to an object. This makes getting object properties by name impossible, though you should still be able to foreach over it. You can also simply cast it back to an array: $results = (array) $obj;. Then, count the array.
This appears to work:
if (current($obj) === false)
echo "is empty\n";
It probably is doing an implicit cast to an array.

php array or not array?

I don't understand... I'm doing something and when I do print_r($var); it tells me that I have an array, so naturally I think I have an array yet when I do
if(is_array($xml->searchResult->item))
it returns false
I use this array with foreach(); in documentation it says that foreach() won't work with anything else but array, so assuming that this is an array that I'm working...
plus, if I try to access it via
echo $xml->searchResult->item[3];
i will get 4th element of my array
print_r will also print objects as though they are arrays.
well, is_array() returns true if your variable is an array, otherwise, it returns false. In your case, $xml->searchResult->item seems not to be an array. What is the output for
var_dump($xml->searchResult->item)
? Another hint: You can determine the type of a variable via gettype().
is_array() returns true only for real php arrays. It is possible to create a "fake" array by using the ArrayAccess class. That is, you can use normal array semantics (such as item[3]) but it is not a real array. I suspect your $item is an object. So use
if($x instanceof ArrayAccess || is_array($x))
Instead.
plus, if I try to access it via echo $xml->searchResult->item[3]; i will get 4th element of my array
That's right, the first element is always 0 unless you specifically change it.
The manual does mention that foreach works on objects as well, and it will iterate over properties.
In your case, the situation is slightly different because I guess you're using SimpleXML, which is yet another special case. SimpleXMLElement has its own iterator, which I assume is hardcoded as it doesn't seem to implement any of SPL's Iterator interfaces.
Long story short, some objects can be used as an array, but they are not one.
Just be careful to check what has been returned by your array. You might have an object with class or stdClass which is empty and you cannot get element from it.

Categories