PHP class return nothing - php

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)

Related

Is it possible to chain static together with non-static method in PHP?

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');

PHP error printing inside class

I'm trying to play with a class and not understand how it works. Some people explained how to pass variables between a function. My problem at the moment is errors. And how to extract errors from the class and print to the screen. My output is username only. How to get errors?
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function get_errors()
{
return $this->errors;
}
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
return $this->errors = "No MySQL connection.";
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
You can not return two time inside a function. But you can achieve what you want like below:-
public function getUserName() {
$this->errors = "No MySQL connection.";
return $this->username.'<br/>'.$this->errors;
}
Note:- this is the solution but your code have no mean. You have to do some useful stuff
try throw exception
public function getUserName() {
if($this->errors) {
throw new Exception($this->errors);
}
return $this->username;
}
$test = new form('name1', 'passw2');
try {
echo $test->getUserName();
} catch(Exception $error) {
echo 'Error:'.$error->getMessage();
}
If you get error you can simple catching this error and output to web,console or error log;
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function getErrors()
{
return $this->errors;
}
public function getPassword()
{
return $this->password;
}
public function getUserName()
{
/* Add some an error to an error's array */
$this->errors[] = "No MySQL connection.";
return $this->username;
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
var_dump($test->getErrors()); /* Get errors from a class */

PHP - Using classes to fetch user info

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

Object function won't execute in PHP

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.

Writing a model for a user (php)

I have a users model that has a lot of properties such as first_name, last_name, email, address, address2...etc
I am writing a php class to manage these properties, but it seems like I am writing a lot of the same code. (Getters and setters). Should I use magic methods to manage this? It seems like an OK idea, but I don't want incorrect properties being set. Any ideas?
<?php
class User
{
private $username;
private $email
private $first_name;
private $last_name;
private $address;
private $address2;
function __construct()
{
}
function getUsername()
{
return $this->username
}
function setUsername($username)
{
$this->username = $username;
}
...
}
?>
Unless you are doing validation on the input, there's no point using getters/setters here in my opinion.
Make the properties public, and override the getters/setters for invalid properties using magic methods:
class User
{
public $username;
public $email;
public $first_name;
public $last_name;
public $address;
public $address2;
public function __get($var) {
throw new Exception("Invalid property $var");
}
public function __set($var, $value) {
$this->__get($var);
}
}
$user = new User;
$user->username = 'foo'; // works
$user->foo = 'bar'; // errors
First of all, can't you use public properties?
If no and your properties does not require any logic when getting/setting, i would use __get and __set.
If you really don't want "incorrect" properties being set (why?), a option could be to use a whitelist of properties that's okay to set:
function __set($key, $value) {
$whitelist = array("firstname", "lastname", ..);
if(!in_array($key, $whitelist))
throw new Exception("Invalid property");
}

Categories