Reputation:
i'm new in php and i have problems with this piece of code
i do not figure out , why 'echo' prints : x ? error 3000
3000 is a key , indeed should be printing "scanner error" ...
what's wrong in my code ? thank you to every one ...
<?php
// ....................................... sym
class Error
{
const lexer = 1000 ;
const parser = 2000 ;
const scanner = 3000 ;
}
final class err extends Error
{
public $stringerr = array (
lexer => "Lexer error" ,
parser => "Parser error" ,
scanner => "Scanner error"
) ;
public function error ( $x )
{
echo "\nx" . " ? " . $stringerr[ $x ] . " error ";
return $x ;
}
}
?>
echo err::error( err::scanner ) ;
output :
x ? error 3000
Upvotes: 0
Views: 110
Reputation: 782
echo is for printing on the screen + in the function you are returning $x that didn't receive any changes.
Try:
return $stringerr[$x];
Instead of:
echo "\nx" . " ? " . $stringerr[ $x ] . " error ";
return $x;
Upvotes: 1
Reputation: 23769
Your mistake is using a non-static property, while calling a static function. You can see the php notice about it:
PHP Notice: Undefined variable: stringerr in file.php on line 19
You should either define the property as static and apply to it via class name:
<?php
class Error
{
const lexer = 1000 ;
const parser = 2000 ;
const scanner = 3000 ;
}
final class err extends Error
{
public static $stringerr = array (
Error::lexer => "Lexer error" ,
Error::parser => "Parser error" ,
Error::scanner => "Scanner error"
) ;
public static function error ( $x )
{
echo "\nx" . " ? " . err::$stringerr[ $x ] . " error ";
return $x ;
}
}
echo err::error( err::scanner ) ;
?>
Prints:
x ? Scanner error error 3000
Mention, that I deliberately defined error function as static.
Or define an instance of this class and use $this
:
<?php
class Error
{
const lexer = 1000 ;
const parser = 2000 ;
const scanner = 3000 ;
}
final class err extends Error
{
public $stringerr = array (
Error::lexer => "Lexer error" ,
Error::parser => "Parser error" ,
Error::scanner => "Scanner error"
) ;
public function error ( $x )
{
echo "\nx" . " ? " . $this->stringerr[ $x ] . " error ";
return $x ;
}
}
$var = new err();
echo $var->error( Error::scanner ) ;
?>
http://www.php.net/manual/en/language.oop5.static.php
Upvotes: 1
Reputation: 10838
If I've understood correctly
err::scanner
= 3000
$stringerr[ $x ]
== $stringerr[3000]
You would need to do err::error('scanner');
or:
public $stringerr = array (
1000 => "Lexer error",
2000 => "Parser error",
3000 => "Scanner error"
);
And, $stringerr[ $x ]
should be $this->stringerr[$x]
Upvotes: 1