PHP - Can't Return User Class Variables Via Getter
All my code is returning is the username... Please help.
index.php
<?php include('user.class'); $user = new user("Jbonnett", "0", "Admin", "Jamie", "Bonnett", "jbonnett@site.co.uk", "01/09/1992"); echo "username: " . $user->getUsername() . "<br/>"; echo "id: " . $user->getId() . "<br/>"; echo "level: " . $user->getLevel() . "<br/>"; echo "Forename: " . $user->getForename() . "<br/>"; echo "Surname: " . $user->getSurname() . "<br/>"; echo "Email: " . $user->getEmail() . "<br/>"; echo "Dob: " . $user->getDob() . "<br/>"; ?>user.class <?php class user { private $username; private $id; private $level; private $forename; private $surname; private $email; private $dob; public function user($username, $id, $level, $forname, $surname, $email, $dob) { $this->setUsername($username); $this->setId($id); $this->setLevel($level); $this->setForename($forename); $this->setSurname($surname); $this->setEmail($email); $this->setDob($dob); } public function destroy() { unset($this->username); unset($this->id); unset($this->level); unset($this->forename); unset($this->surname); unset($this->uemail); unset($this->dob); } public function setUsername($username) { $this->username = $username; } public function getUsername() { return $this->username; } public function setId($id) { $this->id = $id; } public function getId() { return $this->$id; } public function setLevel($level) { $this->level = $level; } public function getLevel() { return $this->level; } public function setForename($forename) { $this->foreName = $forename; } public function getForename() { return $this->forename; } public function setSurname($surname) { $this->surName = $surname; } public function getSurname() { return $this->surname; } public function setEmail($email) { $this->email = $email; } public function getEmail() { return $this->email; } public function setDob($dob) { $this->dob = $dob; } public function getDob() { return $this->dob; } }; ?> Similar TutorialsHi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. Hey, I've not used PHP for a while and never really used classes! I was reading some code today and I saw a statement something like: Code: [Select] $s = &MyClass::("Something"); From reading the PHP Manual it has an example which looks like this for 5.3, however my server still uses 5.2 (.9), how do I do similar using that? Preferably something along these lines... Code: [Select] class spook{ function __construct($n){ if($n==1){ return "hello"; } else { return "goodbye"; } } } $a=spook::(); print $a; Cheers! i.e. What was the old method before the Scope resolution operator? Script:
<?php class Article{ public function fetch_all(){ global $pdo; $query = $pdo->prepare("SELECT * FROM `articles` ORDER BY `article_timestamp` DESC"); $query->execute(); return $query->fetchAll(); } public function fetch_data($article_id){ global $pdo; $query = $pdo->prepare("SELECT * FROM `articles` WHERE `article_id` = ?"); $query->bindValue(1, $article_id); $query->execute(); return $query->fetch(); } /* * These have gotten added later on. */ public function delete($id){ global $pdo; $query = $pdo->prepare("DELETE FROM `articles` WHERE `article_id` = ?"); $query->bindValue(1, $id); $query->execute(); // The "return" here. } public function edit_page($title, $content, $aticle_id){ global $pdo; $query = $pdo->prepare("UPDATE `articles` SET `article_title` = ?, `article_content` = ? WHERE `article_id` = ?"); $query->bindValue(1, $title); $query->bindValue(2, $content); $query->bindValue(3, $article_id); $query->execute(); // The "return" here. } } ?>I have this from a tutorial. In the function "fetch_all()" it uses "fetchAll()" at the spot where the "return" is, and in the function "fetch_data()" it uses "fetch()" at the spot where the "return" is. My Question: What may have to use for the function "delete()" and the function "edit_page()" at the spot where "return" would be? Edited by glassfish, 29 October 2014 - 12:32 PM. I have a form page (referred to as form.php) which is then processed via a submit button, the script then processes the data from the form.php and if it discovers an error it then sets a variable containing the error message my process page contains Code: [Select] if (empty($b_addr)) { $b_addr_error = "Address is required"; $check_failed = TRUE;} header("Location: form.php"); then my form.php contains Code: [Select] $b_addr_error = safe($_GET['b_addr_error']); if (isset($_POST['$b_addr_error'])) { echo "<div class='errorfont' align='center'>'".$b_addr_error."';</div>"; } but the variables do not get passed back to form.php from the process page, any ideas? Thank you. Hi I have a problem with the following: Code: [Select] <?php class ClassA { public $propertyClassName = "ClassB"; public function methodClassName() { return "ClassB"; } } class ClassB { public function bmethod() { echo "great!"; } } //works $a = new ClassA(); $b = new $a->propertyClassName(); $b->bmethod(); //doesn't work $a = new ClassA(); $b = new $a->methodClassName(); $b->bmethod(); ?> Of course I could do Code: [Select] <?php $a = new ClassA(); $className = $a->methodClassName(); $b = new $className; $b->bmethod(); ?>but isn't there a way to do this without saving the method's return to a variable? Thanks in advance flolam Hey guys, So im building a Content Management System for my A2 project in Computing, and i have a dataBase class. Now, i can return one thing, or do things like inserts however im having a problem returning a list of things such as: dataBase.class.php Code: [Select] public static function getNYCPost($table, $limit) { dataBase::_dbConnect(); if($limit == 0) { //debug: echo 'in as 0'; $data = mysql_query("SELECT id, linklabel FROM ".$table." WHERE showing='1' AND id >= 2"); } if($limit == 1) { //debug: echo 'in'; $data = mysql_query("SELECT id, linklabel FROM ". $table ." WHERE showing='1' AND id >= 2 ORDER BY id DESC LIMIT 5"); return $data; } } When i try to do this in the main code: index.php Code: [Select] <?php $list = dataBase::getNYCPost($pages,1); // echo $list; while ($row = mysql_fetch_array($list)) { $pageId = $row["id"]; $linklabel = $row["linklabel"]; $menuDisplay .= '<a href="index.php?pid=' . $pid . '">' . $linklabel . '</a><br />'; } echo $menuDisplay; ?> $list doesnt return anything, the previous method i used in the class was to make a list and an array and put the contents of the query in an array like: Code: [Select] list($list[] = $row); or something i cant quite remember i saw a youtube video tutorial and it worked for them, but it wasnt for me. If anyone knows how i can return various rows from a database it would be appreciated Thanks. I'm not versed in PHP OOP and I have some code that I need to echo out onto a page. I don't know what the meaning of $ct->something is in this code. Is this an array of some type? How do I echo out the $ct->title onto another page? Use a function call? I just don't know what all of the $ct variables are and how to get to them. Any help is appreciated. Code: [Select] function current_theme_info() { $themes = get_themes(); $current_theme = get_current_theme(); if ( ! isset( $themes[$current_theme] ) ) { delete_option( 'current_theme' ); $current_theme = get_current_theme(); } $ct->name = $current_theme; $ct->title = $themes[$current_theme]['Title']; $ct->version = $themes[$current_theme]['Version']; $ct->parent_theme = $themes[$current_theme]['Parent Theme']; $ct->template_dir = $themes[$current_theme]['Template Dir']; $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir']; $ct->template = $themes[$current_theme]['Template']; $ct->stylesheet = $themes[$current_theme]['Stylesheet']; $ct->screenshot = $themes[$current_theme]['Screenshot']; $ct->description = $themes[$current_theme]['Description']; $ct->author = $themes[$current_theme]['Author']; $ct->tags = $themes[$current_theme]['Tags']; $ct->theme_root = $themes[$current_theme]['Theme Root']; $ct->theme_root_uri = $themes[$current_theme]['Theme Root URI']; return $ct; } json_decode returns a stdClass Object. Is there any way where I can get instance of my class instead of the same? I mean If I json_decode the below string then it will provide me instance of stdClass and not instance of Person class {"name":"a"} How to achieve the same? Thanks in advance CSJakharia I am getting the following error: Parse error: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in /Library/WebServer/Dev/classtest/lib/class_userdata.php on line 5 on this class code: Code: [Select] class userdata { public $name = ""; public $city = ""; public $phone = ""; function setData($n, $c, $p) { $name = $n; $city = $c; $phone = $p; } function getData() { $userdata=array('name'=>$name, 'city'=>$city, 'phone'=>$phone); return $userdata; } } I thought that was a proper way to set up some class variables. (http://www.victorchen.info/accessing-php-class-variables-and-functions/). Thanks. Can someone give me a hand on getting this working :p maybe how to use it and what not.. I'm trying but not very successful lol. I want to call the loaduser on the profile page.. <?php include "Database.php"; class User{ //Constructor - Create a new user function User(){ } //Constructor - Load an existing user function LoaddUser($userID){ $this->LoadUser($UserID); } function LoadUser($userID){ //$db = new Database(); $results = mysql_fetch_array(mysql_query("SELECT * FROM userInfo WHERE User_ID = '$userID'")); $UserID = $results[UserID]; $Email_Address = $results[Email_Address]; $Password = $results[Password]; $Name = $results[Name]; $Screen_Name = $results[Screen_Name]; return $results; } } ?> Thanks, Sean What do you think of my user class so far? Room to improve, things to change etc. I'm still getting the hang of this oop thing. Code: [Select] http://pastebin.com/fPFk21k4 Does anyone know if it's possible to call a class with an arbitrary number of variables? I'll explain what I mean. Here is my class construct definition: Code: [Select] function __construct($file, $outFile = 'newpdf.pdf', $fontSize = 70, $alpha=0.6, $overlayMsg = 'N O T F O R S H O P', $degrees = 45) { I know that I have to pass over the $file variable for it to work now. But can I create the class passing just the $file var and the $overlayMsg var? Everything else I would want to leave as default. How would I do that? Thanks Mike I think I need to use $this, but I need to be able to add the two values returned from both of my functions. How would I do that? Code: [Select] public function get_users_edge($uid) { $users_primary->get_users_primary_edge($uid); $users_dynamic->get_users_dynamic_edge($uid); echo $users_primary + $users_dynamic; } I keep running into a bunch of error when I declare the page variable in my model. What syntax do I need to use throughout the class? Code: [Select] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Header_Model extends CI_Model{ var $page = substr(end(explode(DIRECTORY_SEPARATOR, $_SERVER['PHP_SELF'])), 0, -4); function get_page_name() { $this->load->library('common'); $page_names = $this->common->page_names(); $title = (array_key_exists($page, $page_names) !== false) ? $page_names[$page]: ''; if (array_key_exists($page, $page_names) !== false) { $title .= " | Jason Biondo"; } return $title; } function get_js_page_file() { if (file_exists("./assets/js/pages/${page}.js")) { $javascript = "<script type=\"text/javascript\" src=\"./js/pages/${page}.js\"></script>"; } return $javascript; } } I'm confused as to why assigning these variables in the class causes the page not to load... var $RootFolder = '/shyid/'; var $PagePath = str_replace($this->RootFolder, '', dirname($_SERVER['PHP_SELF'])); var $PageSections = explode('/', $this->PagePath); but when i set them on the page, everything works correctly? $head->RootFolder = '/shyid/'; $head->PagePath = str_replace($head->RootFolder, '', dirname($_SERVER['PHP_SELF'])); $head->PageSections = explode('/', $head->PagePath); Insight? Thanks. I'm looking for a more efficient way of declaring variables within a class. What I normally use is a class which is actually a database object. Every time I make a new table in my database I make a new class and new attributes to match the fields in the db table. Looks something like this: Code: [Select] protected static $table_name="myTable"; protected static $db_fields=array('id', 'name', 'address', 'tel_number', 'fax_number'); public $name; public $address; public $tel_number; public $fax_number; //etc. etc. At the moment I am manually adding the attribute, everytime I add a field to the db table. I'm guessing there should be a way to loop through the $db_fields array and add an attribute in the loop? Can anyone help me with the syntax for this. Is there also a way that I don't have to list the fields everytime in $db_fields....can $db_fields not just look at the relevant db table and pull out the field names in some kind of clever method? What would be the simplest way? Do you use a method in the child class? Personally I use Code: [Select] parent::$this->whatever; But I was wondering what you guys do. Hi, I've always used PHP code in my websites in a procedural manner as I come from a html/css background. Now that I want to do projects with more complexity I'm thinking I need to approach development in a more Object Oriented fashion. My question is more a theoretical one. I'm creating a User class and I'm not sure on what is the best practise for putting my functions etc. and where to call them. My project will have 2 different users (Admin & End User) so is it correct to say that the User class should encapsulate all the functions of both of these users ? By that I mean create/delete/modify user, login & change password/forgotten password functionality rather than having a seperate Login class Should I only call the database functions within these methods of the user class as opposed to calling them on the php page where the form data is posted ? For example, if a user logins in and when the form data is posted I currently open a connection, validate data, run the query. In an OO approach would I have just one User class method thats relevant to a particular page functionality ? Say, in pseudo code, for handling a login request loginRequest.php Code: [Select] include User class try { create new user User(); User::login(); } catch Exception() and should my User class look something like this class.User.php Code: [Select] include DBase class class User { var name, var email, var password, function validateInput (email, password) { if (!valid input) throw Exception else return true } function login (email, password){ try { database connection validateInput(); sql to see if user exists and login } catch Exception } } Apologies for this being a bit long winded! thanks tmfl Hello there
After a few years of spending less and less time coding, I've got a lot of catching up to do. Back when I left I usually would run without classes. Now this is a big deal for me today.
I do understand the concept of classes and already did some working models, mostly from my learning process.
Now here is what is bothering me:
<?PHP class database { // Variables public $test; // Constructor public function __construct() { $test = "4"; } // Functions // public function test() { var_dump($this->test); } } $test = new database; $test->test(); ?>Wether I run this script on itself, nor through another file, this does work. What i get is: NULL The constructor does run, I did an echo inside it. Also it does not matter if the variable is public, private or protected - it will be always NULL. Error_reporting is on E_ALL, does not show any errors. What have I overlooked? Hi guys, I am trying something fairly simple but I'm not sure if this would be a good practice. Basically I am using a big class called CommonLibrary that holds common functions as methods and common variables as static variables. But I have some variables here and there like $allAlphabet = range ('a' , 'z'), that cannot be declared as a property because it gives me a parse error. I don't want to call an object for this class because instancing it is of no use. Values will never change with regards to instances. So the next best thing that I tried was declaring all static variables first, and then changing thei property values inside the class __construct with self::$variable = 'somevalue', and then using this code below to assign values to the empty static variables. $dummyObject = new CommonLibrary; unset($dummyObject); echo CommonLibrary::$staticVariable; // This property is NULL before the constructer is triggered. Anyone recommend any better ways of doing this? Thanks in advance! |