Php const or public static

Php const or public static

INSIDE CODE and OUTSIDE CODE

class Item
/**
* This is INSIDE CODE because it is written INSIDE the class.
*/
public $label ;
public $price ;
>

/**
* This is OUTSIDE CODE because it is written OUTSIDE the class.
*/
$item = new Item ();
$item -> label = ‘Ink-Jet Tatoo Gun’ ;
$item -> price = 49.99 ;

?>

Ok, that’s simple enough. I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:
* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it — huge mistake.
* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) — another huge mistake.

Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that’s it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.

INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float — which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.

Читайте также:  Python str to list chars

class Item
/**
* Here’s the new INSIDE CODE and the Rules to follow:
*
* 1. STOP ACCESS to properties via $item->label and $item->price,
* by using the protected keyword.
* 2. FORCE the use of public functions.
* 3. ONLY strings are allowed IN & OUT of this class for $label
* via the getLabel and setLabel functions.
* 4. ONLY floats are allowed IN & OUT of this class for $price
* via the getPrice and setPrice functions.
*/

protected $label = ‘Unknown Item’ ; // Rule 1 — protected.
protected $price = 0.0 ; // Rule 1 — protected.

public function getLabel () < // Rule 2 - public function.
return $this -> label ; // Rule 3 — string OUT for $label.
>

public function getPrice () < // Rule 2 - public function.
return $this -> price ; // Rule 4 — float OUT for $price.
>

public function setLabel ( $label ) // Rule 2 — public function.
/**
* Make sure $label is a PHP string that can be used in a SORTING
* alogorithm, NOT a boolean, number, array, or object that can’t
* properly sort — AND to make sure that the getLabel() function
* ALWAYS returns a genuine PHP string.
*
* Using a RegExp would improve this function, however, the main
* point is the one made above.
*/

if( is_string ( $label ))
$this -> label = (string) $label ; // Rule 3 — string IN for $label.
>
>

public function setPrice ( $price ) // Rule 2 — public function.
/**
* Make sure $price is a PHP float so that it can be used in a
* NUMERICAL CALCULATION. Do not accept boolean, string, array or
* some other object that can’t be included in a simple calculation.
* This will ensure that the getPrice() function ALWAYS returns an
* authentic, genuine, full-flavored PHP number and nothing but.
*
* Checking for positive values may improve this function,
* however, the main point is the one made above.
*/

if( is_numeric ( $price ))
$this -> price = (float) $price ; // Rule 4 — float IN for $price.
>
>
>

?>

Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you. which means you can keep your hair!

If you have problems with overriding private methods in extended classes, read this:)

The manual says that «Private limits visibility only to the class that defines the item». That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the «same» private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent’s private methods. If the child doesn’t see the parent’s private methods, the child can’t override them. Scopes are different. In other words — each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

abstract class base <
public function inherited () <
$this -> overridden ();
>
private function overridden () <
echo ‘base’ ;
>
>

class child extends base <
private function overridden () <
echo ‘child’ ;
>
>

$test = new child ();
$test -> inherited ();
?>

Output will be «base».

If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That’s what it is for:)

A sample that works as intended:

abstract class base <
public function inherited () <
$this -> overridden ();
>
protected function overridden () <
echo ‘base’ ;
>
>

class child extends base <
protected function overridden () <
echo ‘child’ ;
>
>

$test = new child ();
$test -> inherited ();
?>
Output will be «child».

Источник

Php const or public static

Константы также могут быть объявлены в пределах одного класса. Область видимости констант по умолчанию public .

Замечание:

Константы класса могут быть переопределены дочерним классом. Начиная с PHP 8.1.0, константы класса не могут быть переопределены дочерним классом, если он определён как окончательный (final).

Интерфейсы также могут содержать константы . За примерами обращайтесь к разделу об интерфейсах.

К классу можно обратиться с помощью переменной. Значение переменной не может быть ключевым словом (например, self , parent и static ).

Обратите внимание, что константы класса задаются один раз для всего класса, а не отдельно для каждого созданного объекта этого класса.

Пример #1 Объявление и использование константы

class MyClass
const CONSTANT = ‘значение константы’ ;

function showConstant () echo self :: CONSTANT . «\n» ;
>
>

echo MyClass :: CONSTANT . «\n» ;

$classname = «MyClass» ;
echo $classname :: CONSTANT . «\n» ;

$class = new MyClass ();
$class -> showConstant ();

Специальная константа ::class , которой на этапе компиляции присваивается полное имя класса, полезна при использовании с классами, использующими пространства имён.

Пример #2 Пример использования ::class с пространством имён

Пример #3 Пример констант, заданных выражением

class foo const TWO = ONE * 2 ;
const THREE = ONE + self :: TWO ;
const SENTENCE = ‘Значение константы THREE — ‘ . self :: THREE ;
>
?>

Пример #4 Модификаторы видимости констант класса, начиная с PHP 7.1.0

class Foo public const BAR = ‘bar’ ;
private const BAZ = ‘baz’ ;
>
echo Foo :: BAR , PHP_EOL ;
echo Foo :: BAZ , PHP_EOL ;
?>

Результат выполнения данного примера в PHP 7.1:

bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Замечание:

Начиная с PHP 7.1.0 для констант класса можно использовать модификаторы области видимости.

User Contributed Notes 12 notes

it’s possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by ‘get_called_class’ method:
abstract class dbObject
<
const TABLE_NAME = ‘undefined’ ;

public static function GetAll ()
$c = get_called_class ();
return «SELECT * FROM `» . $c :: TABLE_NAME . «`» ;
>
>

class dbPerson extends dbObject
const TABLE_NAME = ‘persons’ ;
>

class dbAdmin extends dbPerson
const TABLE_NAME = ‘admins’ ;
>

echo dbPerson :: GetAll (). «
» ; //output: «SELECT * FROM `persons`»
echo dbAdmin :: GetAll (). «
» ; //output: «SELECT * FROM `admins`»

As of PHP 5.6 you can finally define constant using math expressions, like this one:

class MyTimer const SEC_PER_DAY = 60 * 60 * 24 ;
>

Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain.

A constant is a name for a value (but it’s NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.

So returned values from functions can’t be used, because they will return a value only at runtime.

Arrays can’t be used, because they are data structures that exist at runtime.

One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.

Think about some examples written by some before me:

1. const MY_ARR = «return array(\»A\», \»B\», \»C\», \»D\»);»;
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.

2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can’t work, of course. And it doesn’t make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.

3. Someone spoke about «dynamic» assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let’s take the proposed example:

/**
* Constants that deal only with the database
*/
class DbConstant extends aClassConstant <
protected $host = ‘localhost’ ;
protected $user = ‘user’ ;
protected $password = ‘pass’ ;
protected $database = ‘db’ ;
protected $time ;
function __construct () <
$this -> time = time () + 1 ; // dynamic assignment
>
>
?>

Those aren’t constants, those are properties of the class. Something like «this->time = time()» would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

Conclusion: Don’t try to reinvent constants as variables. If constants don’t work, just use variables. Then you don’t need to reinvent methods to achieve things for what is already there.

I think it’s useful if we draw some attention to late static binding here:
class A const MY_CONST = false ;
public function my_const_self () return self :: MY_CONST ;
>
public function my_const_static () return static:: MY_CONST ;
>
>

class B extends A const MY_CONST = true ;
>

$b = new B ();
echo $b -> my_const_self ? ‘yes’ : ‘no’ ; // output: no
echo $b -> my_const_static ? ‘yes’ : ‘no’ ; // output: yes
?>

const can also be used directly in namespaces, a feature never explicitly stated in the documentation.

const BAR = 1 ;
?>

# bar.php
require ‘foo.php’ ;

var_dump ( Foo \ BAR ); // => int(1)
?>

Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:

class a <
const CONST_INT = 10 ;

public function getSelf () return self :: CONST_INT ;
>

public function getThis () return $this :: CONST_INT ;
>
>
?>

And class b (which extends a)

class b extends a const CONST_INT = 20 ;

public function getSelf () return parent :: getSelf ();
>

public function getThis () return parent :: getThis ();
>
>
?>

Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.

print_r ( $b -> getSelf ()); //10
print_r ( $b -> getThis ()); //20

Источник

Оцените статью