Re: Class Variable Scope Question
| From: | Jochem Maas | Date: | Wed, 15 Mar 2006 21:17:15 +0000 |
| Subject: | Re: Class Variable Scope Question | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-231976@lists.php.net to get a copy of this message | ||
Mike Dunlop wrote:
Hi Guys,
I am wondering how to be able to call a class variable from within an outside function using the "::" syntax: See an example of the logic I am using below:
class myClass {
var $variable = 1;
// this works in php4.
<?php
class myClass { function showVar($key = null) {
static $defvar = "default",
$vars = array(
"a"=>1,"b"=>2,"c"=>3
);
if (empty($key)) {
return $defvar;
} else if (isset($vars[$key])) {
return $vars[$key];
}
}}
function extFunction() {
return myClass::showVar();} echo extFunction(),"\n",
myClass::showVar("a"),"\n",
myClass::showVar("b"),"\n",
myClass::showVar("c"),"\n";
?>
} $obj = new myClass; function extFunction() {don't assume - run the code and find out :-) the fact that you think that it might even be possible that doing myClass::showVar() would cause $this in showVar() to refer to $obj suggests that you don't understand [to some degree] either classes, objects and/or scope (or at least how its implemented/applied in php).return myClass::showVar();} I am assuming this isn't working because by calling myClass::showVar ()
instead of $obj->showVar() "$this" would be undefined...does anyone know how to workaround this (e.g. direct access to a variable via "::"it's hard to define a workaround if we don't know what your trying to achieve and why('why' often speaks volumes :-).
syntax like myClass::variable). Does PHP5 address this at all?yup. :-) please install php5 straight away :-P php -r ' class T { private static $U = "V"; static function W() { return self::$U; } } echo T::W(),"\n"; ' now start reading here, plenty of nice OO features that blow php4 out of the water in that context: http://php.net/php5
Many thanks on this. Best, Mike D ................................................................... Mike Dunlop Director of Technology Development [ e ] miked@m80im.com [ p ] 323.644.7808