PHP - Having Difficulty With Variable Scope Of Required Files In A Class
I'm having a problem with (what I'm almost certain is) variable scope, maybe you can help...
So I've got a parent class that, among other things, gets the name of the filepath, explodes this filepath, checks for files with names that mirror that filepath (without the slashes of course), and includes them if they exist: class ParentClass { public $RootFolder; public $PageSections; function __construct() { global $root_folder; $this->RootFolder = $root_folder; //get all directory names... $cleanse = $this->RootFolder; $pagepath = str_replace($cleanse, '', dirname($_SERVER['PHP_SELF'])); $this->PageSections = explode('/', $pagepath); } function RequireIfExists ($sections, $root_folder, $file_name, $file_type) { foreach ($sections as $i){ if (isset($o)) { $i = $o."/".$i; } $file = $root_folder.$i."/".$file_name.$file_type; if (file_exists($_SERVER['DOCUMENT_ROOT'].$file)) { require ($_SERVER['DOCUMENT_ROOT'].$file); echo "<!--".$file." included -->"; //temporary measure to ensure that the file is at least being called. } $o = $i; } } // so, excuting the function // $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); // on some/sub/folder/index.php // will look for somesectionvars.php, somesubsecitonvars.php & somesubfoldersectionvars.php // and include whichever ones exist. } Then there is a child class that utilizes this function, and successfully requires the file. I know the file is coming through because the echo statement on the page shows up in the code, but I cannot get the variables to pass through? <?php class HtmlHead extends PageBlock{ public $PageKeywords; public $PageDescription; public $PageStyles; public $PageScripts; //------------------------ public $SectionKeywords; public $SectionDescription; //------------------------ public $SiteKeywords; public $SiteDescription; public $SiteStyles; public $SiteScripts; //------------------------ public $CatchAll; function __construct() { parent::__construct(); //$this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //I have tried calling the function here with no luck global $site_description, $site_keywords, $section_description, $section_keywords, $xyz; //also made sure to global the variables from the required page $this->SiteDescription = $site_description; $this->SiteKeywords = $site_keywords; $this->SectionDescription = $section_description; $this->SectionKeywords = $section_keywords; $this->PageDescription = $page_description; $this->PageKeywords = $page_keywords; } function Constructor() { $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //Tried calling the function here as well, no luck global $xyz; //global'd the var i want echo "\n<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; echo "\n<!--Sec Keywords are".$xyz."-->"; //Tried to echo the var... //------------------------Rest of code... } } And here is the page that is being required... <?php echo "<!-- 1234 1234 1234 1234 -->"; //test measure to see if/where file is including $section_keywords = "red, secondary"; $section_description = "this is the red section description"; $xyz = "1234"; //test Var to see if there was a naming conflict with the above two.. ?> What am I overlooking this time? Similar TutorialsUsing PHP Version 5.2.13 My question: How do I access a class and it's methods from an included file? I have an Index.php page that calls two methods: <?php get_header(); ?> <?php get_footer(); ?> and it creates a class in an include file <?php include_once($_SERVER['DOCUMENT_ROOT'].'/includes/common.html');?> $site = new WebSite($site_name); // Creates a bunch of properties, defines some methods, etc... $site->initialize(); <?php get_header(); ?> ends up including a another file (header.php) <?php get_header(); ?> ends up including a another file (footer.php) All calls in Index.php to methods in my class work. ie <?php $site->display_section('column'); ?> But calls in either the header.php or footer.php to methods in my class fail with "Call to a member function is not an object". I understand what the error means but I don't understand why. I thought all functions and classes defined in an include file have global scope. As per PHP.NET's documentation: "When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope." The include that creates the class is something that I have inherited from another developer and I actually can't change the scope. I've tried with global $site = new WebSite($site_name);. It actually breaks the entire site. How can I access classes, properties, methods in an include file? Any help would be appreciated. I've been racking my head for several days now on it and it's probably some newbie thing that I am completely overlooking. I hope I've provided enough background and info. Thanks, Brian Hello! I'm having trouble with a class that extends another, and I don't think I understand the 'extends' concept properly. I've had my nose in various manuals, but I haven't had any luck figuring it out. Here's a simplified version of my code: Code: [Select] class Position { private $latitude = 0; private $longitude = 0; public function getLatitude(){ return $this->latitude; } public function getLongitude(){ return $this->longitude; } } class Coordinates extends Position { function __construct($nlat, $nlong){ $this->latitude = $nlat; $this->longitude = $nlong; } } $lat = -123; $long = 44; $coordFirst = new Coordinates($lat,$long); print($coordFirst->getLatitude()); I expect -123 to be printed, but I always get 0 instead. Could someone let me in on what I'm missing here? Thanks a bunch! Long story short, I have a class that does some data verification and session management. In order to do some of this verification, it needs a database connection. I am using the MDB2 class; here is a sample of the constructor's code: this is a snippet of code from My Class. // FUNCTIONS function __construct() { /* other code here */ // set up our datbase connection global $dsn; // must use global as to include the one *from* the settings.php include $mdb2 =& MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage()); } echo("SESSION CLASS: if you see this, then we're goood!"); // some very crude debugging, please ignore this! } Now, i have another function within this same class: public static function data_validateUserName($safeUserName){ // build the query $q = "SELECT uName FROM Users WHERE username = '$safeUserName'"; $result = $this->$mdb2->query($q); if($result->numRows() >= 1){ // there is 1 or more hits for a username, it is not available! return false; } else if ($result->numRows() < 1){ // there is less than 1 row with that username, we're golden! return ture; } } Inside the constructor, i have correctly set up a MDB2 object. I was able to run some queries and other things on it *inside* the constructor. Because of this, i know that it's settings are correct and it is fully working. However, when i try to use that $mdb2 object inside this other method, i get all sorts of errors about that being a bad reference to an object that essentially does not exist. Now, i tried searching here, and didn't get much help, so apologies. If you've got a link to a similar question, then please post that with a brief explanation of what you searched for to get it... Also, the php.net manual is not very helpful about the scope of objects in this particular setup... so please know that i did pour over that before posting here. Thanks for your time, all. ***** EDIT ****** I've thought about doing it another way: Each function is passed in a reference to the MDB2 object as an argument instead of relying on the one that is *suposed to be* built in to the actual class it's self. Would this be better / more secure / more efficient?! I have an HTML form with a Dropdown list off dates. The Dropdown is populated using PHP and an array... Code: [Select] <?php $concertDates = array('201105071'=>'May 7, 2011 (9:00am - 12:00pm)', '201105072'=>'May 7, 2011 (1:00pm - 4:00pm)', '201105141'=>'May 14, 2011 (9:00am - 12:00pm)'); ?> When my HTML form is re-submitted to itself, what happens to $concertDates?? I was under the impression that it remains alive as long as my script is running... Debbie is there a way of having set variables for a specific include?...maybe be easier for me to explain via code
<?php $bee = 'yes'; include_one "a.php"; include_one "b.php"; // only b.php can grab $bee var ?>im wondering if I can only pass a var to b.php without a.php being able to use the var also? thanks guys i have a text box, the no of text boxes that are displayed are random depending upon the condition of the loop.. hosting[] takes up many no of values <input type='text' name='hosting[]' size='2' /> when the form is submitted i use the following code to access the content of hosting[] $link_no = $_POST['hosting']; $total_actual_links = null; foreach($link_no as $total_link) { $total_actual_links[] = $total_link; } now i get the results in $total_actual_links[].. i want to pass the value of this array into the value of another text box of other form which i get on submission of the 1st form.. i do not knw how shud i do this.. please help In this code... class Model { public function getBook($title) { $allBooks = $this->getBookList(); return $allBooks[$title]; } } Questions: --------------- 1.) What is the scope of $allBooks? Can it be seen outside the function and inside the class? 2.) Could I rewrite things like this... Quote class Model { protected $allBooks; public function getBook($title) { $allBooks = $this->getBookList(); $this->allBooks = $this->getBookList(); return $allBooks[$title]; } } 3.) Sorta off-topic, but could I rewrite this code... Quote $allBooks = $this->getBookList(); return $allBooks[$title]; like this... Quote return $allBooks = $this->getBookList([$title]); TomTees I'm having a complete brainfart right now and can't seem to remember this. Tried looking it up in the manual, but couldn't find an example. Here's what I have: class myclass { function testA { } function testB { } } So that's my basic setup. I want to define a variable. I then want to set it's value in testA(). I then want to be able to access the value in testB(). Where and how do I define this variable? I thought all I had to do was something like: class myclass { public $tempvar=''; function testA { $tempvar="my new value"; } function testB { echo $tempvar; } } But this says that $tempvar is equal to NULL. What am I forgetting? Thanks in advance! I am using a MVC framework and in my controller I have defined a class variable for configurations. In my action I have a call to the configuration class to set the class variable to the current configurations. Code: [Select] public $configArray = array(); public function actionBuild($id) { $this->configArray=Config::model()->getConfigArray($id); $this->buildStep1(); ... } When I echo the configuration in the method it is 10 but when I echo in buildStep1 it is 11. What is the proper way for configArray to be global and updated when I call getConfigArray for use in functions in the class? Hi, im having a problem using a global object in all my scripts and programs. Its a register singleton so it have all the configuration values, etc... Now im doing: 1-I create a script for testing, test.php 2-I include in that script 'errores.php', thats my error system library. 3-The error library include once 'registroglobal.php', thats my file for the global register. 4-Because i can use a lot of systems with a complete library or alone, i created a system where i test if the library module is part of a more greater library or not. If not, it instantiates the global register in errors.php (called in the include in test.php). 5-Here is the problem. Includes add and execute code, so, i must have all errors.php functions and the global register created. 6-If i test the global register in the test.php script, it goes well. 7-But if i call a function of my errores.php system, it says that my global register is undefined. Well, thats all the explanation. Whats going on? How can i solve this? This is more of a technical question that i could not find the answer to pn the php.net manual pages. take the folowing example code: foreach ($array as $key => $value){ $tempvariable = some_property_of($value); } unset($tempvariable); is that unset statement needed? Does PHP automatically destroy the variables once the foreach loop is left? Hi! I need help understanding how to access resource files using ResourceBundle Class and what should be ResourceBundle file format. I have an example of usage in the form of: $r = ResourceBundle::create( 'en', $fileName); but what is the correct format of Resource file? Can it be a format of property file in the form of key=value key=value? or can it be a .txt file of format?: root:table { myName:string { "Here goes my name" } } Can someone share a very simple example of ready to use Resource file with a plain text in it? Thank you! I been wondering how to protect all the files that contain classes, functions and forms in php to prevent direct access to something that the user shouldnt be able to without the proper check's (typing http://server/inc/login.php insteand of http://server/), and i came to this small idea of checking if an object is set or not but i m wondering if this is really the best idea here's what i have (the case bellow will protect an login form to be accessed directly): Code: [Select] <?php if(!isset($mysqlobj)) die(); if( isset( $_POST['username'] ) && isset( $_POST['password'] ) ){ $login = authentication::login( $_POST['username'], $_POST['password'] ); if( $login == true ){ header( 'location:?go=home' ); }else{ $_SESSION['message'] = 'loginfailed'; header( 'location:?go=login' ); } }else{ if( !empty($_SESSION['logged'] ) && $_SESSION['logged'] == true ){ header( 'location:?go=home' ); }else{ ?> <div id="loginform"> <form action="?go=login" method="post"> <table align="center"> <tr> <td><font size="2">Username</font></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><font size="2">Password</font></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Login" /></td> </tr> </table> </form> </div> <?php } } ?> Just looking for an "best practice" i tried google for it but i couldnt get to an straight awnser any enlightment is appreciated. I am rebuilding a CMS system that I have been developing over the last ~6 years. It needs to have many different kinds of modules depending on the installation (Like Drupal or Joomla does) I have a Core class that does the major processing. I am currently developing the part of the system that loads the actual module into the index.php page. While experimenting I came up with an idea that is probably really horrible but I started to wonder if maybe it could actually work well. I am looking for feedback on this Core class function: Code: [Select] public function LoadMods($ModsToLoad) { foreach ($ModsToLoad as $mod) { $MainFile = ABSPATH.DS.$mod.DS.'main.php'; if (file_exists($MainFile)) include ($MainFile); else $this->_MAIN .= 'Error: The "main" file for "'.$mod.'" module could not be found<br/>'; } } It will receive an array of Module names and those names correspond to a directory that holds the "main.php" file for that module. Example: index.php?mod=Photos Will load the "Photos" module. Here is the thing that has me concerned... A module might have it's own class or classes and that class will likely get included in the "main.php" file for that module. What effect is that going to have on my core class because it starts nesting classes inside classes. Is this an efficiency advantage or am I heading down a road paved by code stink? What's you opinion? i use csv file reader class to read csv file...... i need to understand where i should create the sessions array so that i dont have to go back to this class everytime to reteive data..... I have a class that creates a grid from an xml feed. The class file is attached. The grid displays on a page which is defined within the class as follows: Code: [Select] private $results_page = '/foobar.php'; I'm including the same class in multiple folders (the folders are addon domains) so I can have just one copy of the class so it is easy to modify. The problem is that I need to add a variable containing the folder name to the $results_page path, so that when the class executes within each folder, the $results_page is 'FOLDER//foobar.php' I have a file with defines in each folder, and I have tried including that file in the class and using the defined var in the construct, but I can't get it to work. What am I missing? If i declare protected variable in a class how can i access those variable in other class inheriting that class? Can anyone post example code? 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 have a method that is returning a funny variable, it should be returning what is below and when I echo the return from inside the method it is right. Code: [Select] Software/Section but when I goto echo the from outside the class I get the following. It adds a back slash Code: [Select] Software//Section this is the method code and it works fine when I echo the returnValue the value is right Code: [Select] // Creates a dymamic case statement for making a the choice // inside and array foreach (scandir($dir) as $folderItem) { if ($folderItem != "." AND $folderItem != "..") { if (is_dir($dir.$folderItem.DIRECTORY_SEPARATOR)) { $folderItem = $folderItem ; // this allows the the dir to be placed if statements below $folderContents = $this->showPage( $dir.$folderItem ,$getPageGlobal , $subdir); $subdir = ""; // this resets so that ithe value does not get added to main links; } else { // put into if into array if($getPageGlobal== $folderItem) { $pageReturn = $dir . $folderItem; } } } } echo $pageReturn.'<br>'; return $pageReturn; This is the way I am echoing the class. This is when it decides to add the back slash Code: [Select] echo $dynamicMenu->getShowPage(); Using this locally works fine: $html = $name::add_content($name, $html); but i get the double colon error whe using it live. $name is a name of a valid class. What could throw this error when it works locally? |