I am getting the following error from the method presented below:
Notice: Uninitialized string offset: 5 in /path/to/file.php on line 30 Fatal error: Cannot access empty property in path/to/file.php on line 30
private function parse($xml, $index = '') {
echo count($xml->children()); //outputs 6
$count = 0;
foreach ($xml->children() as $key => $value) {
$this->$key[$count] = array();
$count++;
}
}
Any ideas why if I build an multi-dimensional in this way it results in an error?
If I change the assignment to:
$this->$key = array($count = > array());
This simply re-assigns the property each loop.
Thanks
Rich
Imagine you've got a string:
$string = 'abc`;
Doing substring access (which looks like array) will return you the character:
echo $string[2]; # c
Or you get your error when you're out of the index:
echo $string[3]; # null + warning
So now accessing a member of your object $this dynamically:
$this->$string[2]; # access $this->c
However this one breaks hardly:
$this->$string[3]; # access $this->null (not possible)
This gives you your fatal error of an empty property, a property with no name.
This explain what happens in your code, you have not told what you're trying to do so I hope this information will help you to continue with writing your parse function.
You should try to create the array before filling it.
I.e. $this->key = array();
That is, before looping through the XML elements.
Related
php version 5.3.1 with codeigniter 2.0.2
help me, i have errors like this :
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object and Invalid argument supplied for foreach()
Filename: controllers/login.php
Line Number: 20
Controller
parent::__construct();
$this->load->model('option_m');
$option = $this->option_m->get_by(array('nama_opsi' => 'store_option'));
foreach (unserialize($option->value_opsi) as $key => $val) {
$this->data->$key = $val;
}
$this->template->use_asset()->set_judul('Form Login')->set_css('login');
$this->data->metadata = $this->template->get_metadata();
$this->data->judul = $this->template->get_judul();
}
in the sublime text, line number 20 is, but im not sure:
foreach (unserialize($option->value_opsi) as $key => $val) {
$this->data->$key = $val;
Try storing unserialize($option->value_opsi) in an intermediate variable and print it out. I'm betting that's not an array format that foreach can accept.
First verify if $option is valid before using it, otherwise you will end up trying to access values from an invalid return. Suppose your query returned $option = false, then you tried to access a field from it like $option->value, then you will get the same error.
I suggest you to put a if statement before using it:
if($option) { foo; bar; ...}
And use unserialize only if $option->value_opsi is a serialized value.
Hope it helped.
I've written a small static method for my class which returns either $_POST variable if it is set or NULL otherwise. Input elements in HTML form have names with hyphens for example 'customer-name'.
So I think I could access them like this $var = $_POST['customer-name']. But with my method:
public static function getPost($param) {
echo $param." = ".$_POST[$param]."<br/>";
return isset($_POST[$param]) ? $_POST[$param] : NULL;
}
I can not. And I notice some strange behavior when added some echo statements to my method. It cuts off everything after a hyphen, so I got error:
Notice: Undefined index: customer- in .. on line ..
This is how I test it:
$arr = (array)$object;
$newArr = array();
foreach($arr as $key => $val) {
$newKey = str_replace(get_class($object), "", $key);
$newArr[$newKey] = MyObject::getPost(strtolower(get_class($object))."-".$newKey);
}
And this is the output from my test:
...
Notice: Undefined index: customer- in .. on line 116
customer-id =
Notice: Undefined index: customer- in .. on line 116
customer-name =
Notice: Undefined index: customer- in .. on line 116
customer-phonecode =
...
EDIT 1 - I was asked for HTML form:
<form action="" method="post" class="form-horizontal" role="form">
<input type="text" name="customer-name" id="customer-name" class="form-control" placeholder="Name" required="required" autocomplete="off" />
<select id="customer-phonecode" name="customer-phonecode" class="form-control">
<option value="+123"></option>
</select>
</form>
EDIT 2 - Tested on phptester.net on 5.2, 5.3, 5.4, 5.5 php versions. Getting same error.
EDIT 3 - Tested following script. If passing string as key I get element in super global $_POST/an array. But if passing a variable which points to a string, an element cannot be accessed
<?php
$test = array('customer-test1' => 1, 'customer-test2' => 2);
function getPost($param) {
global $test;
$newParam = (string)$param;
echo $param." = ".$test[$newParam]."<br/>";
return isset($test[$newParam]) ? $test[$newParam] : NULL;
}
class Customer {
private $test1;
private $test2;
function __construct() { }
}
$object = new Customer();
$arr = (array)$object;
$newArr = array();
foreach($arr as $key => $val) {
$newKey = str_replace(get_class($object), "", $key);
$newArr[$newKey] = getPost(strtolower(get_class($object))."-".$newKey);
}
Might this be a PHP bug?
This may be a limitation of PHP - when using superglobals such as $_POST, there are some "magical" things going on. PHP converts the names of form elements in many ways, for example
<input type="text" name="hello[mate]" />
Will be accessible as $_POST['hello']['mate'], because the form names are processed as variables. Using dashes is therefore generally not a good idea, because they are not allowed in variable names and probably interfere here. I would advise to only use characters which are allowed for variables in PHP, and replace dashes with underscores.
So the problem was, that casting object to an array adds null characters to array keys. They are not just class name+property name. It's how PHP manages private class properties when casting.
$object = new Customer();
$arr = (array)$object;
print_r(array_map("addslashes", array_keys($arr)));
Outputs:
Array (
[0] => \0Customer\0test1
[1] => \0Customer\0test2
)
Im not sure why var_dump() doesnt show those null bytes. Might be my next question I guess. So those nulls were still there in my static method argument. But why PHP stops right after dash/hyphen?
In PHP we can simply write:
$Tmp= 'hehe';
But for the same in C, we would use the following code:
Char Tmp [4];
Tmp [0] = 'h';
Tmp [1] = 'e';
Tmp [2] = 'h';
Tmp [3] = 'e';
Tmp [4] = '\0';
C handles strings as a character array, it needs a way to define the
last character of the string. This is done using a null byte. A null
byte is donated by \0 in C. So when the program runs, it starts
reading the string from the first character until the null byte is
reached. This creates a problem. As we know, PHP is also implemented
in C. This can become an issue, because some functions in PHP might
handle an input string as they are handled by C.
Sources: #71673, null-byte-injection-php
EDIT 1: Solution added
Solution is to replace '\0' characters as well as class name with "" in my foreach loop:
foreach($arr as $key => $val) {
$newKey = str_replace(array(get_class($object), "\0"), "", $key);
$newArr[$newKey] = getPost(strtolower(get_class($object))."-".$newKey);
}
I keep getting the following error and I was wondering on how to fix?
Fatal error: Unsupported operand types in C:\wamp\www\tuto\core\Controller.php on line 23
Here is line 23.
$this->vars += $key;
Here is the full code below.
public function set($key,$value=null){
if(is_array($key)){
$this->vars += $key;
}else{
$this->vars[$key]= $value;
}
}
+ can be used in different ways but to avoid complications, only use it on numeric values.
When you didnt initially set $this->vars to be an array, it won't work (thx to deceze);
see http://codepad.viper-7.com/A24zds
Instead try init the array and use array_merge:
public function set($key,$value=null){
if (!is_array($this->vars)) {
$this->vars = array();
}
if(is_array($key)){
$this->vars = array_merge($this->vars, $key);
}else{
$this->vars[$key] = $value;
}
}
Examples:
<?php
$test = null;
$t = array('test');
//$test += $t prints the fatal here
$test = array('one');
$test += $t;
// will only print '0 => one'
print_r($test);
$test = array_merge($test, $t);
// will print both elements
print_r($test);
The solution is in the error. You are trying to sum two value that has different types. You are summing array with normal value;
$this->vars += $key;
$key shouldnt be an array
Or second option;
$this->vars should be an array
**PROBLEM YOUR FAILED TO ADDED EQUAL SIGN TO THE VARIABLE WHICH FETCH INFORMATION TO THE DATABASE **
Hell guys i tried to remove PHP - Fatal error: Unsupported operand types this error will occur during us fail to declare the variable correct so you will solve it this error by add the sign "=" Example if you try to type like this:
$sa="SELECT * FROM `anquiz` WHERE user_id = $a";
$af=mysql_query($sa);
while($cv-mysql_fetch_array($af)){
$d1=$cv['id'];
$d2=$cv['answer'];//student answer
$d4=$cv['quiz_id'];// quiz id
$d5=$cv['user_id'];// user id insert his file
$d6=$cv['time'];
you will get error of fatal unsupported operand by sign - on varible that carry the mysql_fetch_array instead of adding = Take that example` by adding that sign you will see an error
$this->vars,
this->$vars,
$this->$vars.
Only number 1 is correct, 2 & 3 are not
I've got an odd error in my PHP code regarding dynamic arrays.
The error outputted is:
Fatal error: Cannot use string offset as an array ... on line 89
This is a portion of my code, it is within a foreach loop, which is looping through settings in a database:
foreach($query->fetchAll() as $row)
{
if($site!=CURRENT_SITE_TEMPLATE)
{
$property = 'foreignSettings';
$propertyType = 'foreignSettingsTypes';
} else {
$property = 'settings';
$propertyType = 'settingTypes';
}
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
settype($this->$property[$row['variable_section']][$row['variable_name']],$row['variable_type']);
$this->$propertyType[$row['variable_section']][$row['variable_name']] = $row['variable_type'];
}
For the sake of the example code, $site is 'admin' and CURRENT_SITE_TEMPLATE is 'admin'.
In addition, $foreignSettings, $foreignSettingsTypes, $settings, and $settingTypes are all defined as arrays in the class scope
The error is on line 89, which is:
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
I originally thought it was because of the $property variable accesing the array, however, this looks like valid legal code in the PHP documentation ( http://php.net/manual/en/language.variables.variable.php in example #1)
Any help on this error would be appreciated.
Thanks
In your given example $property is a string. You are then trying to use that as an array. Strings only has numeric indexes (if you need to use as an array).
The problem is as follows: $this->$property[0] means you access the 0th place of $property which in your case would be the first letter of the string $property. Thus you end up with $this->f or $this->s.
with $this->$property[0][0] you would be trying to access the 0th place of the 0th place of the $property string what results in an error because you try to access the 0th place of the char s what is not possible since the char s can not be referenced as an array.
what you want is $this->{$propperty}[0][0] what means that you try to access the 0th place of the 0th place of the variable that has the name $propperty.
Trying to use a class that expects something like:
$client->firstname = 'bob';
$client->lastname = 'jones';
So I want to pass this data to the script in an array... where the keys and values are set elsewhere. I want to step through the array passing the key and value to the class. Trying to use this:
while($Val = current($CreateClientData)){
$client->key($CreateClientData) = $Val;
next($CreateClientData);
}
getting this:
Fatal error: Can't use method return value in write context in
blahblahpath on line 40.
Line 40 being: $client->key($CreateClientData) = $Val;
How can I do this?
If $client is already an instance of some class, and $CreateClientData is an array, then you probably wan to do something like this:
foreach($CreateClientData as $k => $v) {
$client->{$k} = $v;
}
This assumes of course that every key in the array is a valid member of the $client instance. If not, then you will have to do some additional checking before assigning the value, or you will have to wrap the assignment in a try / catch.
EDIT
The answer as to why your code doesn't work is because PHP doesn't allow for assignment of class properties to certain functions that return values. In your case, key($CreateClientData) returns a key. So you could alter your code and just add
$key = key($CreateClientData);
$client->$key = $Val;
But, the foreach loop is a lot cleaner anyway.
Why don't you use a foreach loop?
foreach($CreateClientData as $key => $val) {
$client->$key = $val;
}