PHP - Calling Object From A Class
I am calling an object from another class in the constructor of first class but when I call it in another function it does not access it's object. Here is the code.
Code: [Select] <?php /* This is controller.php used to control the flow of data between view.php and model.php. This file cotains all the controlling mechanism of the data It was created on 11th Feb 2011 By Narjis Fatima for an Open Source Project and contains all the includes to the database etc. */ include ("view.php"); include ("functions.php"); $name = stripslashes($_GET['username']); $email = stripslashes($_GET['email']); //echo "in controller.php"; check_validate_input($name, $email); $newUser = new controller($name, $email); $action=$_GET['t']; $newUser->display_view($action); class controller { public $my_model; //is an object of model class public $user_info;//=array('id' , 'username' ,'role','email','interests','location', 'homepage'); function __construct($name,$email) { $my_model = new model(); $user_info = $my_model->check_members($name,$email); echo "<pre>"; print_r ($user_info); } function __destruct() { } function display_view($token) { echo "In display function"; echo "<pre>"; print_r ($user_info); if ($this->user_info == NULL) { if (($token=="register")) { show_registration_form(); } else{ show_mailing_form(); } } if ($this->user_info['role'] == "admin") { $myView = new view(); $myView->view_admin_menu(); } if ($this->user_info['role'] == "user") { $myView = new view(); $myView->view_user_menu() ; } }//close of function display_view() } /* name and email cominfg from index.php would be checked by the controoler class to be checked if it a vaild name and email. The database would be connected n the model.php*/ ?> The code for model.php is as follows Code: [Select] <?php //This is model.php created on 10th Feb 2011 .It deals with daytabase connection // //By NArjis Fatima //For the project of EDUForge an Open Source Software //include ("register.php"); class model{ public $dbh; public $user_arr=array('username','password','email','location','interest','homepage'); //cunstructor of model class //function to connect to database function __construct(){ try{ $this->dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } } public function check_members($username,$email) { //get_connected(); $sql = "SELECT * FROM account WHERE (username='" .$username ."' AND email='" .$email."')"; $sth = $this->dbh->prepare($sql); $sth->execute(); $result = $sth->fetch(); /* echo('<pre>'); print_r($result);*/ return ($result); } public function insert_data($user_info) { //$user_info = $user_in; //$dbh; try{ $dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } $dbh->exec("INSERT INTO account (username, userpassword, email, role, location, interest, homepage) VALUES ('" .$user_info['username']."','".$user_info['password'] ."','".$user_info['email']."', 'user','".$user_info['location']."','".$user_info['interests'] ."','".$user_info['homepage']."')"); } } ?> Please somebody help me. I am really stuck. I am also sending my attachment. Similar TutorialsHi Can you call Class A's methods or properties from Class B's methods? Thanks. 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 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. 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 This is probably a quick one. I am pretty new to OOP, in fact somewhat a novice. I am working a lot more with objects lately as my previous "flat" php experience doesn't allow me to create clean and expandable applications. Of course though, questions will always pop up (that's what you guys are for?) One concept I am having trouble understanding, is the method to call a class. What is the difference between?: Code: [Select] <?php $cat = new class(); ?> and just simply: Code: [Select] <?php new class(); ?> Both appear to have the same output from my small amount of practice, but the first way seems strange to me. Being that I am very new to OO PHP, the first way looks like it is just defining a var. But in reality it is calling the class and running it? This seems very backwards to me and I am having a hell of a time understanding it. I am aware that the first way seems to be the "proper" way, but just can't fathom it. Could someone explain this to me a little further? thanks much, I have a PHP config file called config.php. inside the file is simular to this: Quote <?php class JConfig { var $offline = '0'; var $editor = 'tinymce'; var $list_limit = '20'; } ?> From another file, i have included config.php, but how do I call $editor to get "tinymce"? Thanks can someone help me I am trying to call a class function using a varible.... example say i go to index.php?page=contact i want to pull that class with out doing a switch statement can someone help me Code: [Select] <?php $Site = page; $Site->getPage($_GET['page']); ?> Code: [Select] <?php class page extends site { function getPage($page) { return $this->$page; } function Contact() { echo '<h2>Contact test</h2>'; echo '<form> </form>'; } } ?> 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 am working on a site that was made a while ago and on a custom page I am making I am needing to call up variables and my brain is too fried to think up the solution for this. The standing code is this: class site{ var $name = 'Site'; var $data = 'on'; { What I need to do is callup the variables, such as $name, as simple as possible. How would I do this? I am calling my class constructor with the following code class controller{ function _construct($name,$pass){ session_start(); get_model_class($name, $pass); echo "I\'m in controller"; } } function get_model_class($username, $password){ $my_model = new model(); $my_model->check_users($username,$password); } $username = $_POST['username']; $password = $_POST['password']; echo "in controller.php"; $newUser = new controller($username,$password); but it is not entering the constructor Hi How do I turn this: Code: [Select] if($LCname=='Business_solutions'){ $newChild = Business_solutions::find_by_id(1); } In to something like this: Code: [Select] $newChild = $LCname::find_by_id(1); I'm calling lots of class's, and want to make it more dynamic. The 2nd example would be perfect, but that does not work. Is there an alternative? Thanks Dear all , i am trying the following : i have a class named ACCOUNT with many properties in .some of these properties are array , it is like this : Code: [Select] class ACCOUNT { PRIVATE $DB_LINK; PRIVATE $COMP; PRIVATE $BRANCH; PRIVATE $CURRENCY; PRIVATE $GL; PRIVATE $CIF; PRIVATE $SL; PRIVATE $EXIST; PRIVATE $STATUS; private $ACCOUNT_NAME=ARRAY("LA"=>'',"LE"=>'',"SA"=>'',"SE"=>''); private $ACCOUNT_BALANCE =ARRAY('FC_YTD','CV_YTD','CV_BAL','YTD_BAL','BLOCKED_CV','BLOCKED_FC'); private $CY_NAME=ARRAY("LA"=>'',"LE"=>'',"SA"=>'',"SE"=>''); private $ACCOUNT_NAME_USR=ARRAY("LA"=>'',"LE"=>'',"SA"=>'',"SE"=>''); private $LEDGER_NAME= ARRAY("LA"=>'',"LE"=>''); i have created the following method to call any property [code] FUNCTION GET_SPECIFEC_ATT($ATT,$LANG) { $ATT=$ATT."['L$LANG']"; ECHO $this->$ATT; } but i am getting the below error : Notice: Undefined property: ACCOUNT::$BRANCH_NAME['LA'] in D:\wamp\www\EBANK\account.class on line 186 if i used this : Code: [Select] echo $this->BRANCH_NAME['LA']; it is working fine . and the method is working fine i can iam trying to call property which is NOT an array. Can you please help me in what iam doing wrong ? Thanks in advance 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>"; } } }} 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? Hello,
I am having some troubles and was hoping someone could guide me through it.
Q: When ever I try call my get_status function all I get is a white page of nothing, no errors to work from etc... Can anyone here see what I am doing wrong?
PATH: index.php
NOTICE //<<-- KILLS PAGE
<?php spl_autoload_register(function ($class) { include '/lib/' . $class . '.inc'; }); $servers = new servers; echo $servers->get_servers(); echo "STATUS: ".$servers->get_status("0.0.0.0",80); //<<-- KILLS PAGE ?>Page works fine until I want to use the status function, I get no errors or anything just a blank page. PATH: Lib/Servers.inc NOTICE //<<-- KILLS PAGE <?php ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(E_ALL); error_reporting(-1); include_once '../../Global-Includes/ServerStatus/db-connect.php'; //namespace xStatus; class servers { private $db_Hostname = HOSTNAME; private $db_Username = USERNAME; private $db_Password = PASSWORD; private $db_Database = DATABASE; private $dbSQL = ''; function __construct() { } // End Construct public function get_servers(){ $db = new mysqli($this->db_Hostname,$this->db_Username,$this->db_Password,$this->db_Database); $message = ''; // list current servers from database $sql = "SELECT * FROM tbl_servers"; $res = $db->query($sql); if ($res->num_rows > 0) { $message = '<h3>Current Servers</h3>'; while ($row = $res->fetch_assoc()) { $message .= $row['HostGame'] . '<br>'; $message .= $row['HostIP'] . '<br>'; $message .= $row['HostPort'] . '<br>'; $message .= $this->get_status($row['HostIP'],$row['HostPort']) . '<br>'; //<<-- KILLS PAGE! } } $message .= "<br>End of the \"Server List\" "; return $message; } public function get_status(&$ServerIP,&$ServerPort){ if(@stream_socket_client("tcp://".$this.$ServerIP.":".$this.$ServerPort."", $errno, $errstr, 1) !== false) { return "Online"; } else { return "Offline"; } return "Offline"; } } // End class ?>Kind regards and thank you. This is a bit of a more advanced question so I am hoping there are some advanced programmers online at this time . Anyways basically I want to be able to "queue" functions from a class in a single call and am wondering if I am doing it correctly or if there is a better way to do it. Here is my code: <?php class test { private static $one; private static $two; private static $three; public function callOne($val){ $one .= $val; return $this; } public function callTwo($val){ $two .= $val; return $this; } public function callThree($val){ $three .= $val; return $this; } public function print(){ echo $this->one.' '.$this->two.' '.$this->three; } } ?> now when I want to call this I can do: $test = new test(); $test->callOne('one')->callTwo('two')->callThree('three'); $test->callOne('another one'); $test->print(); Is there a better way to do this or is there a different method of doing this? Just wanna make sure I am doing it right lol. why is this not working? <?php class registration{ public $email = $_POST["email"]; public $username = $_POST["username"]; public $password = $_POST["password"]; //var $username = $_POST["confirmPassword"]; function validateFields(){ echo $this->$email; echo $this->$username; echo $this->$password; //echo $this->$confirmPassword; } } registration->validateFields(); ?> Im getting error: Parse error: syntax error, unexpected T_VARIABLE on the first property declaration $email. Hi all
i am using the code below, but am getting the error
Object of class mysqli_result could not be converted to int
<?php $sql="SELECT lng,lng_prefix FROM tbl_languages where active = 1"; $result=mysqli_query($dbConn, $sql)or die(mysqli_error($dbConn)); //problem line if(mysqli_num_rows($result==1)){ ?>The code continues with what I want to happen based on the result. What does the error mean and how do I fix it? Folks, I need to Extract the Content of "[content] => " Class from the output of the below Script: <?php $keywords = file_get_contents('http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q="paintball"'); $keywords = json_decode($keywords); print_r($keywords); ?> Output is like: Quote stdClass Object ( [responseData] => stdClass Object ( [results] => Array ( => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.paintball.com/ [url] => http://www.paintball.com/ [visibleUrl] => www.paintball.com [cacheUrl] => http://www.google.com/search?q=cache:Zcnr-K8jU4YJ:www.paintball.com [title] => PaintBall.com [titleNoFormatting] => PaintBall.com [content] => Information and meeting place for new and experienced players. Features industry news, equipment reviews, information for new players, links to online ... ) [1] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.zephyrpaintball.com/ [url] => http://www.zephyrpaintball.com/ [visibleUrl] => www.zephyrpaintball.com [cacheUrl] => http://www.google.com/search?q=cache:EkBfV3VsT9UJ:www.zephyrpaintball.com [title] => Cheap Paintball Guns - Cheap Paintball Gear - Cheap Paintball Supplies [titleNoFormatting] => Cheap Paintball Guns - Cheap Paintball Gear - Cheap Paintball Supplies [content] => Cheap Paintball Gear - Zephyr Paintball offers a wide variety of cheap paintball guns as well as cheap paintball supplies that can get you into the painball ... ) [2] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.addictinggames.com/paintballthegame.html [url] => http://www.addictinggames.com/paintballthegame.html [visibleUrl] => www.addictinggames.com [cacheUrl] => http://www.google.com/search?q=cache:TM1GFy3lDIQJ:www.addictinggames.com [title] => Paintball - The Game - Free Puzzle and Board Game from AddictingGames! [titleNoFormatting] => Paintball - The Game - Free Puzzle and Board Game from AddictingGames! [content] => Paintball - The Game, a Free Puzzle and Board Game from AddictingGames: Use your skills to paint a path for the ball to get to the magical square. ) [3] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.paintball-online.com/ [url] => http://www.paintball-online.com/ [visibleUrl] => www.paintball-online.com [cacheUrl] => http://www.google.com/search?q=cache:rm9AvRxLLX4J:www.paintball-online.com [title] => Paintball Guns & Markers at Paintball-Online.com [titleNoFormatting] => Paintball Guns & Markers at Paintball-Online.com [content] => The Internet's largest paintball store featuring over 4000 paintball guns, markers and other gear. Free shipping and 10% off for all VIP members. ) [4] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://en.wikipedia.org/wiki/Paintball [url] => http://en.wikipedia.org/wiki/Paintball [visibleUrl] => en.wikipedia.org [cacheUrl] => http://www.google.com/search?q=cache:h3rpb57aWfcJ:en.wikipedia.org [title] => Paintball - Wikipedia, the free encyclopedia [titleNoFormatting] => Paintball - Wikipedia, the free encyclopedia [content] => Paintball is a sport in which players compete, in teams or individually, to eliminate opponents by hitting them with capsules containing food coloring and ... ) [5] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.ansgear.com/ [url] => http://www.ansgear.com/ [visibleUrl] => www.ansgear.com [cacheUrl] => http://www.google.com/search?q=cache:uiYno-g6MOkJ:www.ansgear.com [title] => Paintball - Cheap Paintball Guns, Gear and Paintball Equipment [titleNoFormatting] => Paintball - Cheap Paintball Guns, Gear and Paintball Equipment [content] => Ansgear has Paintball guns and Paintball equipment for everyone. Get your Paintball equipment for cheap. All Paintball gear on sale! ) [6] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => http://www.pbreview.com/ [url] => http://www.pbreview.com/ [visibleUrl] => www.pbreview.com [cacheUrl] => http://www.google.com/search?q=cache:OzXP0G1QzFMJ:www.pbreview.com [title] => Paintball Reviews of Guns, Equipment, Games & More | pbreview.com [titleNoFormatting] => Paintball Reviews of Guns, Equipment, Games & More | pbreview.com [content] => All things paintball on pbreview.com. Paintball gun & equipment reviews, paintball videos, a paintball field locator for paintball games & tournaments. ) [7] => stdClass Object ( [GsearchResultClass] => GwebSearch [unescapedUrl] => Desired Output: Quote [content] => Cheap Paintball Gear - Zephyr Paintball offers a wide variety of cheap paintball guns as well as cheap paintball supplies that can get you into the painball ... [content] => Paintball - The Game, a Free Puzzle and Board Game from AddictingGames: Use your skills to paint a path for the ball to get to the magical square. ) .......................... Till the End of the Page... How can it be achieved? Cheers Natasha T |