My class looks similar to this:
class Foo {
const UNKNOWN = 2;
public function doStuff($var) {
if($var==UNKNOWN) {
echo "Unknown state";
return;
}
// other stuff
}
}
However, I'm getting this error in doStuff():
Use of undefined constant UNKNOWN - assumed 'UNKNOWN'
What am I doing wrong? Can't I define custom constants?
You must use self:: or the class name when accessing the constant in your class:
if($var == self::UNKNOWN) {
echo "Unknown state";
return;
}
Documentation has the example of defining the constants in the PHP class.
self:: will help
class Constants
{
//define('MIN_VALUE', '0.0'); WRONG - Works OUTSIDE of a class definition.
//define('MAX_VALUE', '1.0'); WRONG - Works OUTSIDE of a class definition.
const MIN_VALUE = 0.0; // RIGHT - Works INSIDE of a class definition.
const MAX_VALUE = 1.0; // RIGHT - Works INSIDE of a class definition.
public static function getMinValue()
{
return self::MIN_VALUE;
}
public static function getMaxValue()
{
return self::MAX_VALUE;
}
}
for using every dynamic field in php you must call $this->field
and for using every static field and const in php you must call self::field
example:
class ApiController {
public static $static= "";
public $dynamic= "";
public function __construct() {
$a=$this->$dynamic;
$b=self::$static;
}
}
Related
Look at the following code:
<?php
enum Types:string {
case A = 'a';
case B = 'b';
}
#[Attribute(Attribute::TARGET_CLASS)]
class MyAttribute {
public function __construct(public readonly array $mapping)
{
}
}
#[MyAttribute(mapping: [Types::A->value => ''])]
class Entity {
}
It has error Constant expression contains invalid operations. I would like to use Enum value in my attribute for defining configuration. Seem like it is bug in php. Should it be reported or something?
The problem is that when we call Types::A->value it actually creates instance of an enum, which is not a constant value.
To solve this problem define a constant and reference it.
<?php
abstract class Type {
public const A = 'a';
public const B = 'b';
}
enum TypesEnum:string {
case A = Type::A;
case B = Type::B;
}
#[Attribute(Attribute::TARGET_CLASS)]
class MyAttribute {
public function __construct(public readonly array $mapping)
{
}
}
#[MyAttribute(mapping: [Type::A => ''])]
class Entity {
}
Watch out for this issue in php
I have a simple class in PHP with a constant. In the constructor I'd like to use this constant in a for loop, however both the IDE and PHP say:
Notice: Use of undefined constant DECK_SUITS - assumed 'DECK_SUITS' in /../Deck.php on line 18
Here's the code of my class:
class Deck
{
private $cards = [];
const DECK_SUITS = [Suit::Club, Suit::Diamond, Suit::Heart, Suit::Spade];
const DECK_RANKS = [Rank::Ace, Rank::Two, Rank::Three, Rank::Four, Rank::Five, Rank::Six, Rank::Seven, Rank::Eight, Rank::Nine,
Rank::Ten, Rank::Jack, Rank::Queen, Rank::King];
public function __construct() {
foreach(DECK_SUITS as $suit) {
foreach(DECK_RANKS as $rank) {
$card = new Card($suit, $rank);
$this->cards[] = $card;
}
}
}
So this error is shown for both DECK_SUITS as well as DECK_RANKS in my foreach loop.
I can't find what's wrong with my code.
That's because they're class constants not global constants (created using the define() function), and need to be referenced differently, identifying the class that they're defined in:
foreach(Deck::DECK_SUITS as $suit) {
foreach(Deck::DECK_RANKS as $rank) {
or self::DECK_SUITS and self::DECK_RANKS from within the class where they're defined
i have a little syntax error which i'm not able to sort out, can anyone help ?
Syntax:
Config Class:
Error:
Do not instantiate private variables like that, you should only be using them for declaring properties and simple values.
You cannot declare a private variable (declaring them a return value from a static functions at least) like that, just do it in the constructor __construct() for the object. You will get the same error for any class you do with a private variable declaration like that and setting it as a return value for any function. Try running the below in PHPFiddle and you'll get the same error.
<?php
class A {
private $hi = B::some_function('hi');
}
class B {
public static function some_function(string) {
return $string;
}
}
?>
Instead do something like:
<?php
class A {
private $hi;
public function __construct() {
$this->hi = B::some_function('hi');
}
}
class B {
public static function some_function(string) {
return $string;
}
}
?>
Your syntax is incorrect as I've seen in that picture, simply because you didn't have a closing bracket '}' for the class User.
Just try this one.
Use semicolon for every function call as shown below,
$_table = Config::get('tables/users');
$_seassionsTable = Config::get('tables/user_sessions');
It may be fix your issue.
Why does the following code give me an exception saying that my constant isn't defined
MyClass::myFunction(MyClass::MY_CONST); // THIS GIVES THE ERROR
// This is the class..
class MyClass {
const MY_CONST = 'BLA';
public static function myFunction($key) {
if (!defined($key)) {
throw new Exception("$key is not defined as a constant");
}
}
}
I've tried with
if (!defined($key)) {}
if (!defined(self::$key)) {}
if (!defined(__CLASS__ . $key)) {}
You have to pass it as a string:
public static function myFunction($key) {
if (!defined('self::'.$key)) {
throw new Exception("$key is not defined as a constant");
}
}
MyClass::myFunction('MY_CONST');
As Daniele D points out, for starts you're calling it with the value of the constant, not its name.
And defined needs a different syntax for the parameter when checking class constants, rather than defined constants. It should be
if (!defined('self::' . $key)) {
You need to pass the entire class name and constant as a string.
Like:
MyClass::myFunction('MyClass::MY_CONST');
I trying to learn OOP and I've made this class
class boo{
function boo(&another_class, $some_normal_variable){
$some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $another_class->get($some_normal_variable);
}
}
and I call this somewhere inside the another_class class like
$bla = new boo($bla, $foo);
echo $bla->do_stuff();
But I don't know how to access $bla, $foo inside the do_stuff function
<?php
class Boo
{
private $bar;
public function setBar( $value )
{
$this->bar = $value;
}
public function getValue()
{
return $this->bar;
}
}
$x = new Boo();
$x->setBar( 15 );
print 'Value of bar: ' . $x->getValue() . PHP_EOL;
Please don't pass by reference in PHP 5, there is no need for it and I've read it's actually slower.
I declared the variable in the class, though you don't have to do that.
Ok, first off, use the newer style constructor __construct instead of a method with the class name.
class boo{
public function __construct($another_class, $some_normal_variable){
Second, to answer your specific question, you need to use member variables/properties:
class boo {
protected $another_class = null;
protected $some_normal_variable = null;
public function __construct($another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $some_normal_variable;
}
function do_stuff(){
return $this->another_class->get($this->some_normal_variable);
}
}
Now, note that for member variables, inside of the class we reference them by prefixing them with $this->. That's because the property is bound to this instance of the class. That's what you're looking for...
In PHP, constructors and destructors are written with special names (__construct() and __destruct(), respectively). Access instance variables using $this->. Here's a rewrite of your class to use this:
class boo{
function __construct(&another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $this->another_class->get($this->some_normal_variable);
}
}
You need to capture the values in the class using $this:
$this->foo = $some_normal_variable