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 */
Related
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 been trying to retrieve data from backendless database using PHP but i get this error.
I followed the documentation but there is no much details written.
I have been trying to retrieve data from backendless database using PHP but i get this error.
I followed the documentation but there is no much details written.
Below is my code
<?php
require_once('Plant.php');
use backendless\Backendless;
include "vendor/backendless/autoload.php";
Backendless::initApp('API-KEY', 'API-KEY', 'v1');
$first_contact = Backendless::$Persistence->of('Plant')->findFirst();
$first_contact->getName();
<?php
class Plant {
private $userId;
private $tempLimit;
private $name;
private $lightLimit;
private $lastWatered;
private $humidityLimit;
private $currentTemp;
private $currentHumidity;
private $currentLight;
public function __construct() {
}
public function getName() {
return $thsi->name;
}
public function setName( $name ) {
$this->name = $name;
}
public function getUserId() {
return $thsi->userId;
}
public function setUserId( $userId ) {
$this->userId = $userId;
}
public function gettempLimit() {
return $thsi->tempLimit;
}
public function setTempLimit( $tempLimit ) {
$this->tempLimit = $tempLimit;
}
public function getLightLimit() {
return $thsi->lightLimit;
}
public function setLightLimit( $lightLimit ) {
$this->lightLimit = $lightLimit;
}
public function getLastWatered() {
return $thsi->lastWatered;
}
public function setLastWatered( $lastWatered ) {
$this->lastWatered = $lastWatered;
}
public function getHumidityLimit() {
return $thsi->humidityLimit;
}
public function setHumidityLimit( $humidityLimit ) {
$this->humidityLimit = $humidityLimit;
}
public function getCurrentTemp() {
return $thsi->currentTemp;
}
public function setCurrentTemp( $currentTemp ) {
$this->currentTemp = $currentTemp;
}
}
I am not getting an output for the following piece of code. I cant seem to find the reason for this error.
Heres the code for the config.php
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS','somepwd');
define('DB_NAME','prac');
class Play
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private $connection;
function __construct()
{
$this->open_connection();
}
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public function open_connection()
{
$this->connection=mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
}
public static function find_all() {
return self::find_by_sql("SELECT * FROM users");
}
public static function find_by_sql($sql)
{
$result_set=mysql_query($sql,$this->connection);
$object_array=array();
while($row=mysql_fetch_array($result_set))
{
$object_array[]=self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record)
{
$object=new self;
foreach ($record as $k => $value) {
if($object->has_attribte($k))
{
$object->$k=$value;
}
}
return object;
}
private function has_attribte($att)
{
$some=get_object_vars($this);
return array_key_exists($att, $some);
}
}
$play=new Play();
?>
Heres the code for the index.php
<?php
include('config.php');
$user=Play::find_all();
echo $user->username;
?>
So i am basically trying to instantiate an object to a query result but it is not working. I get no output. Please help.
I am trying to write a small engine in PHP to handle data but i keep on getting this error:
Fatal error: Class 'Factory\dataHandler' not found in /Applications/MAMP/htdocs/Imperial/lp/php/dataPhraserController.php on line 12
Been now trying to find a way of solving the problem but not luck.....
My code:
DataFactory.php
<?php
namespace Factory;
class dataHandler{
protected $firstName;
protected $lastName;
protected $email;
protected $confirmEmail;
protected $phoneNumber;
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setConfirmEmail($confirmEmail)
{
$this->confirmEmail = $confirmEmail;
}
public function setPhoneNumber($phoneNumber)
{
$this->phoneNumber = $phoneNumber;
}
public function getFirstName()
{
var_dump($this->firstName);
}
public function getLastName()
{
return $this->lastName;
}
public function getEmail()
{
return $this->confirmEmail;
}
public function getPhoneNumber()
{
return $this->phoneNumber;
}
}
dataPharserController.php:
<?php
namespace PhraserController;
use Factory\dataHandler;
class DataPhraser
{
private $object;
public function __construct()
{
$this->object = new dataHandler;
}
public function pharseFirstName()
{
if(!isset($_POST['first_name']))
{
$this->object->setFirstName($firstName = null);
var_dump($_POST['first_name']);
}else{
$this->object->setFirstName($firstName = $_POST['first_name']);
}
}
}
$test = new DataPhraser();
$test->pharseFirstName();
The idea is to collect data from a submitted html form, can someone help me.. thx
Place this in one of your config files that are loaded before everything
DEFINE('LIB_DIR', '/path_to_library_dir_of_project/');
function AutoloadDefault($ClassName)
{
$File = LIB_DIR.'/' . $ClassName. '.php';
// echo 'Default:'.$File.'<br/>';
if (file_exists($File))
{
require_once($File);
}
}
spl_autoload_register('AutoloadDefault');
Then just point to right LIB_DIR folder. spl_autoload_register will load the class file