I'm getting this error
Fatal error: Cannot use [] for reading in... on line 26
Checking all the threads that have been made here on this error, I still cannot figure it out. Looking at my code there's nothing I'm doing wrong.
<?php
class Person
{
//Variables for personal information//
private $navn;
private $adresse;
private $postnummer;
private $poststed;
private $telefonnummer;
private $fodselsdato;
public function __construct($navn, $adresse, $postnummer, $poststed, $telefonnummer, $fodselsdato)
{
$this->navn = $navn;
$this->adresse = $adresse;
$this->postnummer = $postnummer;
$this->poststed = $poststed;
$this->telefonnummer = $telefonnummer;
$this->fodselsdato = $fodselsdato;
}
//Creates an array to store education for a person//
private $utdanning = array();
//Function to add education to the array//
public function leggTilUtdanning(Utdanning $utdanning)
{
$this->utdanning[] = $utdanning;
}
}
//Class for education
class Utdanning
{
private $institusjon;
private $studieretning;
private $grad;
private $startet;
private $ferdig;
public function __construct($institusjon, $studieretning, $grad, $startet, $ferdig)
{
$this->institusjon = $institusjon;
$this->studieretning = $studieretning;
$this->grad = $grad;
$this->startet = $startet;
$this->ferdig = $ferdig;
}
}
$person1 = new Person('Dave Lewis', 'Downing Street 14', 0442, 'Northville', 98765432, '17.05.1975');
$utdanning = new Utdanning('Harvard', 'Economics', 'Bachelor', 2013, 2016);
$person1->leggTilUtdanning($utdanning);
?>
The error comes from the line inside the function where I'm trying to add an Utdanning-object to the array. It's funny, cause I tried this very same method of doing it on another project, using the exact same syntax, and it worked perfectly. Furthermore, I don't understand why it says I'm trying to read from the array, when I'm actually adding to it.
Does anyone have an idea what's going on here?
EDIT: I circled the problem and made a more simple version of the code so you can see for yourself.
So, just to mark this solved, I got rid of the problem simply by rewriting the characters inside the method leggtilUtdanning. Appears to have been some sort of character encoding-problem like you pointed out, but I have absolutely no idea how that happened. Anyway, thanks for all the help.
Related
I'm writing a code in PHP OOP and I'm trying to send $_POST data
filtered by one Class function to another Class function that will add
the data to database. Specifically login and password in registration
form.
I have 3 Classes that will do that:
Is simple Class that handles connection to database (I think it is not necessary to put code here)
Is the Class that filters the coming $_POST-s:
class Filter extends Dbconnect {
protected $login;
protected $haslo;
public function regFilter() {
if (isset($_POST))
{
foreach($_POST as $key => $val)
{
$filterVal = strip_tags($val);
$filterVal = htmlspecialchars($filterVal);
$filterVal = stripslashes($filterVal);
$filterVal = str_replace("\\", "", $filterVal);
$filter = array(
$key => $filterVal
);
foreach($filter as $key => $val)
{
echo "[$$key]";
echo "$val";
$
{
$key
} = $val;
}
}
return $filter = array(
'login' => $login,
'haslo' => $haslo
);
}
else
{
echo "Proszę podać login i hasło!";
}
}
}
Class that will get login and password and send it to DB:
class Dbinsert extends regFilter{
//protected $login;
//protected $haslo;
protected $query;
protected $dbo;
public function insert(){
//$this->extract = extract($filter);
//$this->login = $login;
//$this->haslo = $haslo;
$this->connect();
$this->query = "INSERT INTO uzytkownik (id, nazwa, haslo) VALUES ('', :login, OLD_PASSWORD(:haslo))";
if(!$result = $this->connect()->prepare($this->query)){
echo 'Zapytanie nie powiodło się';
}
else{
$result->bindParam(':login', $login);
$result->bindParam(':haslo', $haslo);
$login = $_POST['login'];
$haslo = $_POST['haslo'];
$result->execute();
}
$dbo = null;
}
}
Now when I try to send data from form with objects:
$rejestruj = new Dbinsert();
$filtruj = $rejestruj->regFilter();
var_dump($filtruj);
$dodaj = $filtruj->insert();
I get the following result:
[$login]login
[$haslo]password123
array(2) { ["login"]= string(5) "login" ["haslo"]= string(11) "password123" }
Fatal error: Call to a member function insert() on array in `E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\register.php` on line 78
Which doesn't surprises me since: login and haslo is returned from
"foreach" loop in class Filter (which is just for testing) "array(2)"
is returned from "var_dump($filtruj);"(to check if it is actually
working) and error is returned since I send an array to Class
Dbinsert - but in the function I put "extract" to get the variables.
How can I send just the variables from this filtered array to class
Dbinsert?
Edit: As #Twinfriends suggested I corrected function insert in class Dbinsert to actually use prepared statement, thats why (for now) login and haslo variables are reffering to $_POST. Now I need answer to my question.
(First time posting, thanks for edit suggestions, also any advice is appreciated since I'm quite the beginner
in PHP)
Sorry that it took so long to answer, I totally forgot your question. Well, lets take a look at your problem, hope to solve it.
I try to explain it as good as I can, so that you understand whats going on. First of all, lets look at your error message
Fatal error: Call to a member function insert() on array in
E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\register.php on line 78
Okay. Call to a function on array... lets have a look at how you actually call the function:
$rejestruj = new Dbinsert();
$filtruj = $rejestruj->regFilter();
var_dump($filtruj);
$dodaj = $filtruj->insert();
And exactly here is your error. You have to understand that you call methods on objects and pass your data to this methods, not to call the methods on your data. What do I mean with that?
$rejestruj is your Dbinsert object. You create it in your first line of code here. Then, you call the regFilter function on it. Still anything is fine. As you see, var_dump gives you the expected results. So the error has to be on your last lane of code. And indeed, you try to call the method insert() on your array. And that won't work, since your array don't know any method called insert().
The right call to the method would be (Not the final one!!!):
$dodaj = $rejestruj->insert();
Now the method call should work. But in fact, it won't insert anything. Why? Because your insert() method try to bind the variables $login and $haslo - two variables the method don't know. So we need to pass the data in your method. To do that, you have to do the following changes:
Method call:
$rejestruj->insert($filtruj); // $filtruj contains your array
And your Dbinsert should look like:
class Dbinsert extends Dbconnect{
protected $query;
protected $dbo;
public function insert($data){
$this->connect();
$this->query = "INSERT INTO uzytkownik (id, nazwa, haslo) VALUES ('', :login, OLD_PASSWORD(:haslo))";
if(!$result = $this->connect()->prepare($this->query)){
echo 'Zapytanie nie powiodło się';
}
else {
$result->bindParam(':login', $data["login"]);
$result->bindParam(':haslo', $data["haslo"]);
$result->execute();
}
$dbo = null;
}
}
I hope your code works with this changes. So, while in my opinion the code should work now, I want to mention that there are many things you could improve. For example, you're not programming real "object-oriented" ... its more some pseudo OOP you're writing here. Some things are quite bad practice (could be done much easier). I don't want to dive to deep into details, since I don't know if you're interested in it. If you wish I can give you some more advises, but only if you wish.
Otherwise I really hope my answer help you. If the whole thing still doesn't work, please let me know so I can look at it again.
Have a nice day ;)
Edit:
Since it seems I haven't been clear enough, here the code how it should look like now:
$rejestruj = new Dbinsert();
$filtruj = $rejestruj->regFilter();
$dodaj = $rejestruj->insert($filtruj);
<?php
class TEST{
public $x=1;
private $y=2;
public function changeA($val){
//$this->x = $val;
echo "X-->".$this->x;
}
private function changeB($val){
//$this->y = $val;
echo "Y-->".$this->y;
}
}
$a = new TEST();
$a->changeA(3);
#
$a->changeB(4);
This is really bugging me, I use all the correct syntax but I got error right on the line I do CLASS test.
Parse error: parse error in file.php on line x
Tested:
-Remove vars, functions, new objects. nothing fix it.
====Updated Code above, but still, the same error.
I think there is something wrong with my php... I am now running all different kind of code, even echo return the same error. I think there is some other trouble with my php setup.
===Last update
I was using Ajax to passing value and write into a php file with 755 and public access. It was seem like a kind of process hiccup. Now it functioning correctly. But the example still, really useful. Well, don't know what is the vote down for, its seem make sense to mark reason for vote down as well like the ones who need to vote to close it. So SO can as least know the reason for the vote down. Interesting right? Someone who actually care about improving this.
Class method definitions are not statements, and therefore should not be terminated with ;.
This means that the }; on lines 11, 16 and 17 should simply be } instead.
On another note, I don't know what version of PHP you're using. I'm using PHP 5.5 and got a very clear message:
Parse error: syntax error, unexpected ';', expecting function (T_FUNCTION) in test.php on line 11
It's always good to practice on simple examples to make its own idea about how it works.
This might help to clarify things.
class test
{
public $x;
private $y;
function __construct() {
echo "-- Constructor --<br/>";
$this->changeX(1);
$this->changeY(2);
echo "-- Exiting Constructor --<br/>";
}
public function changeX($val) {
$this->x = $val;
echo "X-->".$this->x."<br/>"; // for debugging purpose only
}
private function changeY($val) {
$this->y = $val;
echo "Y-->".$this->y."<br/>"; // for debugging purpose only
}
public function changeYprivate($val) {
$this->changeY($val); // can call private method here
}
public function getY() {
return $this->y;
}
}
$objTest = new test();
echo "X is ".$objTest->x." and Y is ".$objTest->getY()."<br/>";
$objTest->changeX(3);
$objTest->x = 10; // ok x is public, it can be modified
$objTest->changeYprivate(4);
// $a->changeY(4); // Error : cannot call this function outside the class !
// $objTest->y = 20; // Error : y is private !
// echo $objTest->y; // Error ! Can't even read y because it's private
echo "X is ".$objTest->x." and Y is ".$objTest->getY()."<br/>";
Output:
-- Constructor --
X-->1
Y-->2
-- Exiting Constructor --
X is 1 and Y is 2
X-->3
Y-->4
X is 10 and Y is 4
I have a php file that previously used to write xml data with tags. Now I'm trying to make it a little remoteobject based. So instead of writing xml I'm trying to return a class object that consists some big multidimensional array. The problem is it is causing a high latency. I'm not sure if it's my php file that is causing latency problem.
My php code :
class output{
public $grid;
public $week;
public $name;
var $_explicitType = "org.test.output";
}
class manager1{
function init($params,$arrayOut)
{
$action = $params[0];
switch ($action)
{
case "reload": return $this->Reload($arrayOut);break;
default:return $this->form($arrayOut);
}
}
private function Reload($arrayOut)
{
$this->getSlice();
$arrayOut->grid = $this->gridValue();
$arrayOut->week = 'no data';
return $arrayOut;
}
private function form($arrayOut)
{
$arrayOut->grid = $this->gridValue();
$arrayOut->week= $this->getAllWeek($this->ThisYear);
return $arrayOut;
}
}
AS-3 code calling php function:
private function init():void{
var _amf:RemoteObject = new RemoteObject();
var params:Array = new Array(); //parameters array
params.push("default");
var arrayOut:output = new output();//strongly typed class
_amf.destination = "dummyDestination";
_amf.endpoint = "http://insight2.ultralysis.com/Amfhp/Amfphp/"; //amfphp home directory
_amf.source = "manager1"; //the php class which will be called
_amf.addEventListener(ResultEvent.Result, handleResult);
_amf.init(params,arrayOut);
}
private function handleResult(event:ResultEvent):void
{
datagrid.dataProvider = event.result.grid;
}
And there is also a class named output in my application:
package org.test{
public class output
{
public var grid:Array;
public var week:Array;
}
}
I'm using this to pass value to flex remoteobject using amfphp.
Actually, it's fairly easy to figure out.
You can use the Network Monitor that is part of Flash Builder. It shows the Request Time and the Response Time, so you can get a pretty good idea if the issue is with the PHP side or the Flex side. You can also see the size of the response.
Be aware that Remote Objects mixed with Multidimentional arrays can be larger than you think, but again the Network Monitor will help you figure out that.
I want to validate a form with php.
Therefor I created a class "benutzer" and a public function "benutzerEintragen" of this class to validate the form:
class benutzer
{
private $username = "";
private $mail = "";
private $mail_check = "";
private $passwort = "";
private $passwort_check = "";
public $error_blank = array();
public $error_notSelected = array();
public $error_notEqual = array();
public function benutzerEintragen () {
$textfields[0] = $this->username;
$textfields[1] = $this->mail;
$textfields[2] = $this->mail_check;
$textfields[3] = $this->passwort;
$textfields[4] = $this->passwort_check;
foreach ($textfields as $string) {
$result = checkFormular::emptyVariable($string);
$error_blank[] = $result;
}
In the function "benutzerEintragen" i filled the variables "username,mail" and so on with the appropriate $_POST entries (not shown in the code above). The call
checkFormular::emptyVariable($string)
just returns "TRUE" if the field is not set or empty otherwise FALSE.
Now when i try to create a new instance of this class, execute the function and get access to $error_blank[0] the array is empty!
if (($_SERVER['REQUEST_METHOD'] == 'POST')){
$BENUTZER = new benutzer();
$BENUTZER->benutzerEintragen();
echo $BENUTZER->error_blank[0];}
So the last line is leading to a "Notice: Undefined offset: 0". It seems to be related to the array structure, because if i do
echo $BENUTZER->mail;
I get any input I wrote in the form, which is correct. Also the foreach loop seems to do the right thing when i run the debugger in phpEd, but it seems like the array "error_blank" is erased after the function is executed.
Any help would be greatly appreciated. Thanks in advance.
There is a scope problem here. You do have a class attribute with the name. Unlike in Java where using a local variable with the same name as a class variable automatically selects the class attribute this is not the case in PHP.
Basically you are saving your output in a local variable which gets discarded once you leave the function. Change $error_blank[] = $result; to $this->error_blank[] = $result; and you should be fine.
First of all this seems overly complicated way to do a simple task, but that wasn't actually the question.
You are creating a new $error_blank variable that is only in function scope. If you wish to use the class variable you should use $this->error_blank[]
I'm trying to create a PHP function that adds an event to a google Calendar. It appears to be building the object correctly but it throws a "Call to a member function getDOM() on a non-object in FeedEntryParent.php" error when trying to add the event. Here is the abbreviated class with only the constructor and the function that adds the event:
class GCal_datasource {
private $user = 'xxxxxxx';
private $pass = 'xxxxxxxxx';
private $client;
private $gdata_cal;
private $calendar;
private $visibility;
public function __construct($settings = NULL){
session_start();
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_HttpClient');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
if($settings == NULL){
$settings = array();
$settings['calendar'] = 'default';
$settings['visibility'] = 'full';
}
$this->calendar = $settings['calendar'];
$this->visibility = $settings['visibility'];
$this->client = $this->get_ClientLoginHttpClient();
$this->gdata_cal = new Zend_Gdata_Calendar($this->client);
}
public function create_event($fields){
$gc = $this->gdata_cal;
$new_event = $this->gdata_cal->newEventEntry();
echo '<pre>';
print_r($fields);
echo '</pre>';
if(isset($fields['quick_add'])){
$new_event->content = $gc->newContent($fields['quick_add']);
$new_event->quickAdd = $gc->newQuickAdd(true);
} else if (isset($fields['title']) && isset($fields['when'])) {
$new_event->title = $fields['title'];
$where = $gc->newWhere($fields['where']);
$new_event->where = array($where);
$desc = $gc->newContent($fields['desc']);
$new_event->content = $desc;
$new_event->content->type = 'text';
$new_event->when = self::build_when_array($fields['when']);
if(isset($fields['web_content'])){
$new_event->link = web_event_array($fields['web_content']);
}
}
echo '<pre>';
print_r($new_event);
echo '</pre>';
$gc->insertEvent($new_event);
return $created_event->id->text;
}
}
The error (I believe) is how I am calling insertEvent() towards the end of the code. The only reason I think that is I only get the error when it exists and if I remove it the echo above it prints out the Event object as intended.
Anyone with a better grasp of the Goggle PHP API that can lend me a hand I would greatly appreciate.
I had this problem.
I think you have to change string
$new_event->title = $fields['title'];
to
$new_event->title = $service->newTitle($fields['title']);
Call to a member function getDOM() on a non-object in FeedEntryParent.php means that somewhere in the file named "FeedEntryParent.php" you have called getDOM() on a variable and that variable is not an object and so does not have a getDOM() method.
Nowhere in the code you posted is a call to getDOM(), so the error is not generated in the posted code.
Track down that call to getDOM(). The error usually gives you a line number. See what variable you are calling the method on. That variable is not an object. Find where that variable is set - that's probably where your problem is.