note 103532 deleted from language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 Apr 2011 23:10:58 +0000 |
| Subject: | note 103532 deleted from language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178960@lists.php.net to get a copy of this message | ||
Note Submitter: php.net (at) bruchmann-web (dot) de
----
As keith tyler showed variables defined outside a class aren't available inside a class even
with notification like:
$myVar = 'myText';
class myClass {
function myFunc() {
global $myVar;
echo 'My Var won't be shown: '.$myVar;
}
}
Like 'e dot klerks ...' and 'carlos dot garciadm ...' wrote the global scope of
variables isn't always wanted (or should I write: is nearly always not wanted?).
From this point of view it's better to take a solution like this:
<?php
class foo {
/*
* Including file with Variable-Definitions.
* The defined path can be overriden by parameter.
* With special getter- & setter-functions
* you could also change 'public' to 'protected' or 'private'
*/
public function initData ($conf = array()) {
if (is_readable($conf['file'])) {
require_once($conf['file']);
}
else {
require_once('/path/to/file/myFile.php');
}
// requires $bar being defined in the file:
$this->bar = $bar;
}
public function printBar () {
echo $this->bar;
}
}
?>
-----
myFile.php:
--
<?php
$bar = 'my home is my castle.';
?>
-----
Now call the class like this:
<?php
include_once(myClassFile.php);
$myFoo = new foo;
$myFoo->initData(); or $myFoo->initData(array('file' =>
'/path/to/file/myFile.php'));
$myFoo->printBar();
?>
This way the variables can be assigned much easier now and you needn't global scope.
Furthermore you've a clear defined configuration-interface where the included file is a
configuration-file with the required definitions and the option to override from outside of the
class.
General hint:
It's up to you to validate any files especially if the file and data come frome outside (i.e.
by http via curl), therefore - like written in the comment - you can change the visibility (private,
protected, public) of variables and functions and insert validators or cast or quote the incoming
data. It may be required to read and validate the file (as string!!) before inclusion to assure that
no functions and file- or database-queries are defined. Furthermore keep care on the writing-rights
to files on your system / server.
But work on security is a general item and not binded to my solution.