PHP - Php Oop Class Return
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. Similar TutorialsHey, 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? 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. 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; } }; ?> 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 have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Hi, 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. Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? I have a class in which I have a function called connection. I am now trying to call this function from another class, but it will not work. It works if I put the code in from the other function rather than calling it but that defeats the purpous. class locationbox { function location() { $databaseconnect = new databaseconnect(); $databaseconnect -> connection();{ $result = mysql_query("SELECT * FROM locations"); while($row = mysql_fetch_array($result)) // line that now gets the error, mysql_fetch_array() expects parameter 1 to be resource, boolean given //in { echo "<option>" . $row['location'] . "</option>"; } } }} I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability. How does one go about using one class inside another? For example, building a class that does some series of functions, and uses a db abstraction layer class in the process? Hi all, I have two classes. Registration and Connection. Inside a registration.php I include my header.php, which then includes my connection.php... So all the classes should be declared when the page is loaded. This is my code: registration.php: <?php include ('assets/header.php'); ?> <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($data, $table){ foreach($this->fields as $key => $value){ mysql_query("INSERT INTO graphs ($this->fields) VALUES ('$data[$key]')"); } mysql_close($connection->connect); } function validateFields(){ $connection = new connection(); $connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data, $this->table); } } $registration = new registration(); $registration->validateFields(); ?> <?php include ('assets/footer.php'); ?> At this point I cannot find my connection class defined on another included/included page. $connection = new connection(); $connection->connect; config.php (included within header.php) <? class connection{ public $dbname = '**'; public $dbHost = '**'; public $dbUser = '**'; public $dbPass = '**'; public $connect; function connect(){ $this->connect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die ('Error connecting to mysql'); mysql_select_db($this->dbname, $this->connect); } } ?> Any ideas how to call it properly? Well the title may seem a bit confusing, but heres an example: Code: [Select] <?php class User{ public $uid; public $username; protected $password; protected $email; public $usergroup; public $profile; public function __construct($id){ // constructor code inside } public function getemail(){ return $this->email; } public function getusergroup(){ return $this->usergroup; } public function getprofile(){ $this->profile = new UserProfile($this->uid); } } class UserProfile(){ protected $avatar; protected $bio; protected $gender; protected $favcolor; public function __construct($id){ // constructor code inside } public function formatavatar(){ // avatar formatting code inside } public function formatusername(){ // format username? } } ?> As you can see, the User class(an outer class) has a property called Profile, which can be instantiated as a UserProfile object(an inner class). The two objects have distinct functionalities, but there are times when the UserProfile object needs to access property and methods from the user object. I know its easy for outer class to access methods from inner class by using the single arrow access operator twice, but how about the other way around? Lets say from the above example the userprofile can format the username displayed to the screen by adding a sun to the left of the username if the usergroup is admin, a moon if the usergroup is mod, and nothing if its just a member. The usergroup property is stored in the outer class, and can be accessed with this $user->getusergroup() method only. I know I can always do the hard way by passing a user object to the method's argument, but is there an easier way for the inner class UserProfile to access properties/methods for outerclass User? If so, how can I achieve that? return (int) $value VS return $value
What is the purpose of using int in a bracket? return (int) $value
Which is the best and safest method?
Thank you
Hey all. My site has a config database table that has a column showlogin to set whether or not login functionality is enabled. I'm playing around with MySQLi, Classes, and Returns. My return is always 1. Where am I going wrong? test.php <?php // Start Session session_start(); // Production Settings ini_set('display_errors', 1); mysqli_report(MYSQLI_REPORT_ALL); include 'db.php'; $mysqli = new mysqli($host, $user, $pass, $db); class styles { function showlogin($show) { global $mysqli; $select = $mysqli->query("SELECT showlogin FROM config LIMIT 1"); $value = $select->fetch_object(); if ($value->showlogin = 1) { return 1; } return 0; } } $login = new styles(); echo $login->showlogin($show); ?> |