I’m kinda confused, I’m new to OOP PHP, so can’t stop my function get empty values.
I have an index.php file where I have:
<?php
require_once('../../includes/functions.php');
require_once('../../includes/database.php');
require_once('../../includes/user.php');
$user = new User();
$user->username = 'test';
$user->password = '1234';
$user->firstname = 'test1';
$user->lastname = 'test2';
User::create();
// $user->traceStatement();
?>
I have a User class that extends Databaseobject class:
user.php:
<?php
require_once('database.php');
class User extends DatabaseObject {
protected static $tableName = 'users';
protected static $tableID = 'id';
public $id;
public $username;
public $password;
public $firstname;
public $lastname;
public function traceStatement() {
echo $this->username;
echo $this->password;
echo $this->firstname;
echo $this->lastname;
}
}
?>
and here’s a snippet of create function from DatabaseObject class:
public function create() {
global $database;
$calledClass = get_called_class();
$class = new $calledClass;
$sql = "INSERT INTO ".$calledClass::$tableName." (username, password, firstname, lastname) VALUES ('";
$sql .= $database->escapeValue($class->username)."', '";
$sql .= $database->escapeValue($class->password)."', '";
$sql .= $database->escapeValue($class->firstname)."', '";
$sql .= $database->escapeValue($class->lastname);
$sql .= "')";
if($database->query($sql)) {
$cass->id = $database->insert_id();
return true;
}else {
return false;
}
}
As far as I understand the idea is that
on my index.php file i’m declaring varibales of User class, these info are sent to user.php and I’m also calling create() function from databaseobject class through User:: class, and my info inside variables will be sent to create function.
in the database I’m getting blank fields.
I tried to hardcode the variables inside my user.php – and everything work (first I thought I wasn’t getting data from user.php).
When it worked I thought maybe I’m not gettind data from index.php to user.php but it turned out that when I wrote function traceStatement() – I got back the data in index.php file…
So maybe someone here know what’s my problem, what am I doing wrong?
Rather than
User::create();, you should use$user->create().And your
create()method should change to: ($this is very important in the OOP world)}