1
First, within a class I have a method, in that method I have a parameter (for now) and declare some variables in its scope. Therefore, I also declare functions within the scope of the method, and as you all know, every function has its own scope.
The problem is that in the scope of the functions I declared in the scope of the method the variables I declared earlier are undefined, and so I cannot access them. How do I get around this? I need to access variables from the previous scope in the scope of these functions.
That’s a part of the function I have in my class, that’s where I’m having problems.
public static function parse($buf) {
$i = 0; $chr; $cod;
// $i, $chr, $cod e $buf
// são todas invisíveis no escopo das funções abaixo.
/* Iterate each char in $buf. */
function itchr($c) {
for (; $chr = $buf[$i]; ++$i) {
$cod = getchrcode($chr);
if ($c() === false)
break;
}
}
/* Consume $buf string until $c returns truth value. */
function consumetil($c) {
$result = (object) array(
"matched" => false,
"value" => ""
);
for (; $chr = $buf[$i]; ++$i) {
$cod = getchrcode($chr);
if ($c()) {
$result->matched = true;
break;
} else $result->value .= $chr;
}
return $result;
}
/* Consume a little identifier in $buf */
function consumeid() {
return consumetil(function() {
return !isIdentifierPart($cod);
});
}
}
@Theprohands you want to pass by reference inside
use
?– novic
Yes, also forgot to warn, PHP does not accept the use of the keyword
'use'
when the function name has been declared, so it does not work to do this normally in my code. First I had to transform my functions into variables, as in your first example. That is, the implementation example ofuse
in the answer does not work.– Klaider
@Theprohands true !!! I even removed from the answer and if you use only
self::
?– novic
self
would be a reference to the class instance, right? And::
is just a form of index? I’m not very experienced in PHP, so I ask.– Klaider
That
self
would access the methods or variablesstatic
– novic
@Theprohands I made more editions with
static
would look like this. You could not use this code in the form of instances?– novic
I also thought about it, but I think it would make a loss of performance since it would have to be doing lookup for
"self"
repeatedly. I can useself::
in future in other classes since this would be to interpret a string– Klaider
Let’s go continue this discussion in chat.
– novic