PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I am trying to prepare a small script to use for a demonstration, and I am getting an odd error. It only happens in one condition, and only once, after which the script works fine, even though I don't see what's different the second time through.
Warning: Cannot use a scalar value as an array in /home/daniel/public_html/codescraps/notes_class.php on line 25
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: Posting Code in the Forums to learn how to do it too.
@Pickle: I considered that, but I don't see how exactly that's happening. This is for a short presentation, there are two PHP files, one that contains a class.
<?php
class noteList{
private $noteFile = 'notes.data';
public $asArray;
public function __construct(){
if(is_file($this->noteFile)){
$this->asArray = unserialize(file_get_contents($this->noteFile));
}else{
$this-asArray;
}
}
public function view($id){
echo $this->asArray[$id].'
<br/><br/>
<a href="?remove='.$id.'">Remove Note</a>
';
}
public function write($note){
//these two produce errors when trying to write for the first time, but then are OK.... wt*!? <-- Pardon my bad language in my comments
$this->asArray[] = $note;
$this->asArray = array_values($this->asArray);
file_put_contents($this->noteFile, serialize($this->asArray));
}
public function remove($id){
unset($this->asArray[$id]);
$this->asArray = array_values($this->asArray);
file_put_contents($this->noteFile, serialize($this-asArray));
}
}
?>
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: Posting Code in the Forums to learn how to do it too.
file_get_contents() does not return a serialized string, it returns an array. Consequently, unserialize() returns boolean FALSE - a scalar value. Later, in write() you try to treat $this->asArray as an array.
Edit: As ~ Syntac said below, file_get_contents() returns a string, not an array.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.