I'm running Eclipse Indigo with PDT and Xdebugger (all latest versions) and a LAMP server on Ubuntu 11.04.
While debugging, an object function (see code below) won't execute; the debugger just defaults - the variables window goes completely blank and it just freezes up. The page won't load either, it just stays in a loading state.
Everything is fine up to the point where I start calling functions on the object.
Suggestions?
Here's the code:
<?php
require_once 'user.php';
require_once 'fetcher.php';
require_once 'inscriber.php';
$uname=$_POST['regname'];
$upass=$_POST['regpass'];
$ufirst=$_POST['regfirst'];
$ulast=$_POST['reglast'];
$uemail=$_POST['regemail'];
$uphone=$_POST['regphone'];
$user = new User();
$user->setUsername($uname); // THIS IS WHERE IT FREEZES UP
$user->setPassword($upass);
$user->setFirstname($ufirst);
$user->setLastname($ulast);
$user->setEmail($uemail);
$user->setPhone($uphone);
$inscriber = Inscriber::getInscriberInstance();
$success = $inscriber->inscribeUser($user);
?>
<?php
class User{
private $username;
private $password;
private $userID;
private $firstname;
private $lastname;
private $phone;
private $email;
public function getUsername(){
return $username;
}
public function setUsername($var){
$this->$username = $var;
}
///
public function getPassword(){
return $password;
}
public function setPassword($var){
$this->$password = $var;
}
///
public function getUserID(){
return $userID;
}
public function setUserID($var){
$this->$userID = $var;
}
///
public function getFirstname(){
return $firstname;
}
public function setFirstname($var){
$this->$firstname = $var;
}
///
public function getLastname(){
return $lastname;
}
public function setLastname($var){
$this->$lastname = $var;
}
///
public function getPhone(){
return $phone;
}
public function setPhone($var){
$this->$phone = $var;
}
///
public function getEmail(){
return $email;
}
public function setEmail($var){
$this->$email = $var;
}
}
$this->$username = $var;
This is a "dynamic property". PHP tries to replace $username with the content of the variable. The variable doesn't exists, so the resulting $this-> = $var just fails
$this->username = $var;
(non-static) properties are always called without the $.
Additional in the getters you are using local variables
public function getUsername(){
return $username;
}
Don't know, why you (at least try to) use properties in setters, but use local variables in getters
public function getUsername(){
return $this->username;
}
Sidenote: "objects functions" are called "methods"
Your syntax is not quite correct (in this case). You want to do this:
//...
public function getUsername(){
return $this->username; //added $this->...
}
public function setUsername($var){
$this->username = $var; //no $-sign before 'username'
}
//...
This goes for all the other functions, too.
Related
I like PHP, but I miss some of the constructs from other languages that although don't do anything for performance, make the code look cleaner and possibly more maintainable. I'm thinking of Visual Basic days and the "with" statement.
So ideally in PHP we could do this:
with($myWellDescribedInstance) {
->property1="string";
->property2=1;
->property3=2;
->myMethod();
}
Instead of
$myWellDescribedInstance->property1="string";
$myWellDescribedInstance->property2=1;
$myWellDescribedInstance->property3=2;
$myWellDescribedInstance->myMethod();
Is there anything like this in PHP?
You can implement a fluent interface on any class just by having a function return $this.
This is mostly used for setters, but of course it works for any method for which you would normally not have a return value.
For example:
class Person
{
protected $name = '';
protected $surname = '';
protected $email = '';
public function getName()
{
return $this->name;
}
public function getSurname()
{
return $this->surname;
}
public function getEmail()
{
return $this->email;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
}
Usage:
$person = new Person;
$person->setName('John')
->setSurname('Doe')
->setEmail('johndoe#email.com');
Of course, calling the method (for example) setName or withName would be entirely up to you.
Another idea might be to have both a setName method (which doesn't return anything) and a withName method (which returns $this), but that might be a bit of an overkill.
If you use "setters" instead of direct property access you can chain methods.
class A {
private $a;
private $b;
public function setA($a)
{
$this->a = $a;
return $this;
}
public function setB($b)
{
$this->b = $b;
return $this;
}
public function doSomething()
{}
}
$a = new A();
$a->setA('a')
->setB('b')
->doSomething();
Here is my sample code Class User but not working when I added the static method with the public methods:
<?php
namespace App\Classic;
class User
{
public $username;
public static $upassword;
public $age;
public $message;
public function username($username)
{
$this->username = $username;
echo $this->username."<br>";
return $this;
}
public static function password($upassword)
{
self::$upassword = $upassword;
echo self::$upassword."<br>";
}
public function age($age)
{
$this->age = $age;
echo $this->age."<br>";
return $this;
}
public function message($message)
{
$this->message = $message;
echo $this->message."<br>";
return $this;
}
}
and this is the side effect of chaining method:
$user = new User();
$user::password('secret')
->username('admin')
->age(40)
->message('lorem ipsum');
I dont know what is the logic behind doing this, but still this solution will be helpful.
Try this code snippet here
<?php
namespace App\Classic;
ini_set('display_errors', 1);
class User
{
public $username;
public static $upassword;
public static $currentObject=null;//added this variable which hold current class object
public $age;
public $message;
public function __construct()//added a constructor which set's current class object in a static variable
{
self::$currentObject= $this;
}
public function username($username)
{
$this->username = $username;
echo $this->username . "<br>";
return $this;//added this statment which will return current class object
}
public static function password($upassword)
{
self::$upassword = $upassword;
echo self::$upassword . "<br>";
return self::$currentObject;
}
public function age($age)
{
$this->age = $age;
echo $this->age . "<br>";
return $this;
}
public function message($message)
{
$this->message = $message;
echo $this->message . "<br>";
return $this;
}
}
$user = new User();
$user::password('secret')
->username('admin')
->age(40)
->message('lorem ipsum');
I'm just beginner with PHP OOP. I have a class and output is empty:
$test = new form('name1', 'passw2');
$test->getName();
and class:
<?php
class form
{
protected $username;
protected $password;
protected $errors = array();
function _construct($username, $password){
$this->username=$username;
$this->password=$password;
}
public function getsomething() {
echo '<br>working'. $this->getn() . '<-missed';
}
public function getName(){
return $this->getsomething();
}
public function getn() {
return $this->username;
}
}
?>
And output is only text without username:
POST working
working<-missed
Where is name1?
I've modifed your code a bit and added some examples to play around with.
This should get you started.
class form
{
protected $username;
protected $password;
protected $errors = array();
// construct is a magic function, two underscores are needed here
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
// functions starting with get are called Getters
// they are accessor functions for the class property of the same name
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
}
public function render() {
echo '<br>working:';
echo '<br>Name: ' . $this->username; // using properties directly
echo '<br>Password:' . $this->password; // not the getters
}
}
$test = new form('name1', 'passw2');
// output via property access
echo $test->username;
echo $test->password;
// output via getter methods
echo $test->getUserName();
echo $test->getPassword();
// output via the render function of the class
$test->render();
Hi You have used _construct it should be __contrust(2 underscores)
I have created a class Person, who contain a person. Here is my code:
<?php
class Person {
private $age;
private $firstName;
private $lastName;
private $optional;
function __construct($id) {
// Load all settings form database, because the person already exists.
}
function __construct($age, $firstName, $lastName, $optional) {
$this->age = $age;
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->optional = $optional;
}
function setFirstName($name) {
$this->firstName = $name;
}
function setLastName($name) {
$this->lastName = $name;
}
function setOptional($key, $value) {
$optional[$key] = $value;
}
function setAge($age) {
$this->age = $age;
}
function getFirstName() {
return $this->firstName;
}
function getLastName() {
return $this->lastName;
}
function getOptional($key) {
return $optional[$key];
}
function getAge() {
return $this->age;
}
}
?>
First: This person will be created if a new user fill a form on the web page (and stored to database) and this person will also be used when the web app want some information about the current user.
How do I interact this class with the database? I guess that I could create two constructors as I have done (I think that you could do like this in java). The first constructor is for when constructing an already registered user, and therefore it will load all information from the database. The second constructor is for when a new user is registered, and it should send all information to the database. Is this the right way to handle the database?
Assume the connection to the database and all references to tables and cells is correct... how could I get something like this working?
class User
{
private $_display;
private $_email;
public function __construct($username)
{
$fetch_user = mysql_query("SELECT * FROM `registered_users` WHERE `user_name`='$username'");
$fetch_user = mysql_fetch_array($fetch_user);
$this->_display = $fetch_user['user_display'];
$this->_email = $fetch_user['user_email'];
}
}
$person1 = new User('username');
echo "Information: " . print_r($person1, TRUE);
the problem is it returns nothing. Doesn't thrown an error or anything when debugged. Is it viable method though? :S
Here is roughly what I would do:
<?php
class User{
private $username;
private $data;
public function __construct($username){
$this->username = $username;
if($this->valid_username()){
$this->load();
}
}
private function load(){
// Let's pretend you have a global $db object.
global $db;
$this->data = $db->query('SELECT * FROM registered_users WHERE user_name=:username', array(':username'=>$this->username))->execute()->fetchAll();
}
public function save(){
// Save $this->data here.
}
/**
* PHP Magic Getter
*/
public function __get($var){
return $this->data[$var];
}
/**
* PHP Magic Setter
*/
public function __set($var, $val){
$this->data[$var] = $val;
}
private function valid_username(){
//check $this->username for validness.
}
// This lets you use the object as a string.
public function __toString(){
return $this->data['user_name'];
}
}
How to use:
<?php
$user = new User('donutdan');
echo $user->name; //will echo 'dan'
$user->name = 'bob';
$user->save(); // will save 'bob' to the database