Abstract constants in PHP - Force a child class to define a constant

Asked
Active3 hr before
Viewed126 times

9 Answers

classabstractconstants
90%

Is there a way I can force a child class to define a constant (which I need to use in one of the abstract class internal methods) ?,PHP Interfaces support constants. It's not as ideal because you would have to remember to implement the interface on every child class so it kind of defeats the purpose partially.,However... you could check to see if the constant is defined in the parent class's constructor. If it doesn't, throw an Exception., 3 This is better then the accepted answer. If an abstract class depends on the child class, define an abstract method to declare this dependency and use the method to get the value from the implementing class. – Kwebble Jun 9 '16 at 7:43

In this example, the abstract, parent class Foo forces all its children to declare the variable NAME. This code runs fine, outputting Donald. However, if the child class Fooling did not declare the variable, the fatal error would be triggered.

< ? php

abstract class Foo {

   // Self-referential 'abstract' declaration
   const NAME = self::NAME;

}

class Fooling extends Foo {

   // Overrides definition from parent class
   // Without this declaration, an error will be triggered
   const NAME = 'Donald';

}

$fooling = new Fooling();

echo $fooling::NAME;
load more v
88%

In this example, the abstract, parent class Foo forces all its children to declare the variable NAME. This code runs fine, outputting Donald. However, if the child class Fooling did not declare the variable, the fatal error would be triggered.,This may be a bit of a ‘hack’, but does the job with very little effort, but just with a different error message if the constant is not declared in the child class.,However... you could check to see if the constant is defined in the parent class's constructor. If it doesn't, throw an Exception.,This is the best way I can think of doing this from your initial description.

In this example, the abstract, parent class Foo forces all its children to declare the variable NAME. This code runs fine, outputting Donald. However, if the child class Fooling did not declare the variable, the fatal error would be triggered.

< ? php

abstract class Foo {

   // Self-referential 'abstract' declaration
   const NAME = self::NAME;

}

class Fooling extends Foo {

   // Overrides definition from parent class
   // Without this declaration, an error will be triggered
   const NAME = 'Donald';

}

$fooling = new Fooling();

echo $fooling::NAME;
load more v
72%

I noticed that you can't have abstract constants in PHP.,Is there a way I can force a child class to define a constant (which I need to use in one of the abstract class internal methods) ?,A constant is a constant; there is no abstract or private constants in PHP as far as I know, but you can have a work around:,Now you can have different sets of configuration which the helper class relies on:

Sample Abstract Class

abstract class Hello {
   const CONSTANT_1 = 'abstract'; // Make Abstract
   const CONSTANT_2 = 'abstract'; // Make Abstract
   const CONSTANT_3 = 'Hello World'; // Normal Constant
   function __construct() {
      Enforcer::__add(__CLASS__, get_called_class());
   }
}

This would run fine

class Foo extends Hello {
   const CONSTANT_1 = 'HELLO_A';
   const CONSTANT_2 = 'HELLO_B';
}
new Foo();

Bar would return Error

class Bar extends Hello {
   const CONSTANT_1 = 'BAR_A';
}
new Bar();

Songo would return Error

class Songo extends Hello {

}
new Songo();

Enforcer Class

class Enforcer {
   public static
   function __add($class, $c) {
      $reflection = new ReflectionClass($class);
      $constantsForced = $reflection - > getConstants();
      foreach($constantsForced as $constant => $value) {
         if (constant("$c::$constant") == "abstract") {
            throw new Exception("Undefined $constant in ".(string) $c);
         }
      }
   }
}
load more v
65%

I noticed that you can't have abstract constants in PHP.,Is there a way I can force a child class to define a constant (which I need to use in one of the abstract class internal methods) ?,A constant is a constant; there is no abstract or private constants in PHP as far as I know, but you can have a work around:,I want to do something like this: or even this would work for me: but neither compiles. Is there a syntax for this, or will I be forced to use make this an inte...

Sample Abstract Class

abstract class Hello {
   const CONSTANT_1 = 'abstract'; // Make Abstract
   const CONSTANT_2 = 'abstract'; // Make Abstract
   const CONSTANT_3 = 'Hello World'; // Normal Constant
   function __construct() {
      Enforcer::__add(__CLASS__, get_called_class());
   }
}
load more v
75%

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child class, and follow the usual inheritance and signature compatibility rules. , Class Abstraction ,Example #2 Abstract class example,Example #1 Abstract class example

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
load more v
40%

abstract class Hello {
   const CONSTANT_1 = 'abstract'; // Make Abstract
   const CONSTANT_2 = 'abstract'; // Make Abstract
   const CONSTANT_3 = 'Hello World'; // Normal Constant
   function __construct() {
      Enforcer::__add(__CLASS__, get_called_class());
   }
}
22%

Sorry, the page you are asking for was not found in this WEB site or it is not available anymore. You may look at the index page instead, from which all the contents of this WEB site are accessible and the latest changes are listed in reverse chronological order.

 Page Not Found (HTTP error code 404)

load more v
60%

Summary: in this tutorial, you will learn about PHP class constants and how to use them effectively.,To define a constant of a class, you use the const keyword. For example:,Use the const keyword to define a class constant.,Sometimes, you need to define a constant that is specific to a class. In this case, you can use the PHP class constants.

To define a constant of a class, you use the const keyword. For example:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   } < ? php

class Circle {
   const PI = M_PI;
}
Code language: Python(python)
load more v
48%

TypeScript enforces that a derived class is always a subtype of its base class.,Just like with const, let, and var, the initializer of a class property will be used to infer its type:,How TypeScript infers types based on runtime behavior,TypeScript has some special inference rules for accessors:

Here’s the most basic class - an empty one:

tsclass Point {}
Try
load more v

Other "class-abstract" queries related to "Abstract constants in PHP - Force a child class to define a constant"