Php class var declaration

Php class var declaration

It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is public .

Note:

Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.

It’s also possible for interfaces to have constants . Look at the interface documentation for examples.

It’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self , parent and static ).

Note that class constants are allocated once per class, and not for each class instance.

Example #1 Defining and using a constant

class MyClass
const CONSTANT = ‘constant value’ ;

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

echo MyClass :: CONSTANT . «\n» ;

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

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

The special ::class constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:

Example #2 Namespaced ::class example

Example #3 Class constant expression example

const ONE = 1 ;
class foo const TWO = ONE * 2 ;
const THREE = ONE + self :: TWO ;
const SENTENCE = ‘The value of THREE is ‘ . self :: THREE ;
>
?>

Example #4 Class constant visibility modifiers, as of PHP 7.1.0

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

Output of the above example in PHP 7.1:

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

Note:

As of PHP 7.1.0 visibility modifiers are allowed for class constants.

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

Источник

PHP Class Variable (Declaration With Examples)

php class variable

In this article, we will learn about PHP Class Variables Declaration in a simple way using examples.

By the end of this tutorial, we’ll have a better understanding of what a class variable is in PHP, with example programs. Before we begin, if you missed any of our prior lessons, you can review the topics in our PHP Tutorial for Beginners.

What are Properties?

According to PHP documentation, member variables in a class are known as properties. They may also be referred to as fields, but for the sake of this discussion, the term properties shall be used.

As of PHP 7.4, they are defined with at least one modifier (such as visibility, static keyword, or, as of PHP 8.1.0, read-only), optionally (except for read-only properties), followed by a type declaration, then a normal variable declaration. This declaration may contain an initialization, but it must consist of a constant value.

Note: Using the var keyword instead of a modifier to declare class properties is deprecated.

Note: A property declared without a visibility modifier is public by default.

Non-static properties may be accessed within class methods by using -> (Object Operator): $this->property (where property is the property’s name). The :: (Double Colon) is utilized to access static properties: self::$property . For additional details on the distinction between static and non-static attributes, see Static Keyword.

The artificial variable when a class method is invoked from within an object context, $this is accessible within the method. $this is the value of the object that is calling.

Example of Property Declaration

Note: There are several functions to handle classes and objects. See the reference for Class/Object Functions.

Type Declarations

With the exception of callable, property definitions can include Type declarations as of PHP 7.4.0.

Example of Typed Properties in PHP Class Variables

id = $id; $this->name = $name; > > $user = new User(2468, "Prince"); var_dump($user->id); var_dump($user->name); ?>

The above example will output:

If typed properties are not initialized before access, an Error is thrown.

Example of Accessing Properties in PHP Class Variables

numberOfSides = $numberOfSides; > public function setName(string $name): void < $this->name = $name; > public function getNumberOfSides(): int < return $this->numberOfSides; > public function getName(): string < return $this->name; > > $triangle = new Shape(); $triangle->setName("square"); $triangle->setNumberofSides(4); var_dump($triangle->getName()); var_dump($triangle->getNumberOfSides()); $circle = new Shape(); $circle->setName("circle"); var_dump($circle->getName()); var_dump($circle->getNumberOfSides()); ?>

The above example will output:

string(6) "square" int(4) string(6) "circle" Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization

Readonly Properties in PHP Class Variables

Since PHP 8.1.0, a property can be declared with the readonly modifier, which prohibits the property from being modified after initialization.

Example of Readonly Properties in PHP Class Variables

prop = $prop; > > $test = new Test("sample text"); // This is a Legal read var_dump($test->prop); // output would be string(11) "sampletext" // Illegal reassignment. It does not matter that the assigned value is the same. $test->prop = "sampletext"; // Error: Cannot modify readonly property Test::$prop ?>

Note: The readonly modifier is only applicable to typed properties. Using the mixed type, a read-only property without type constraints can be generated.

Note: Not supported are readonly static properties.

A readonly property can only be initialized once, and only inside the declaration’s scope. Any additional assignment or modification of the property will result in an exception of type Error.

Example of Illegal Initialization of Readonly Properties in PHP Class Initialize Variables

 $test1 = new Test1; // Illegal initialization outside of private scope. $test1->prop = "sample text"; // Error: Cannot initialize readonly property Test1::$prop from global scope ?>

The above example will output:

Fatal error: Uncaught Error: Cannot initialize readonly property Test1::$prop from global scope

Note: A readonly property with a default value is essentially the same as a constant and therefore not particularly useful.

The above example will output:

Fatal error: Readonly property Test::$prop cannot have default value

Note: Once initialized, readonly properties cannot be unset using the unset() method. However, prior to initialization, it is possible to unset a readonly property from the scope where it was declared.

Modifications are not always simple assignments; the following will also generate an Error exception:

 > $test = new Test; $test->i += 1; $test->i++; ++$test->i; $test->ary[] = 1; $test->ary[0][] = 1; $ref =& $test->i; $test->i =& $ref; byRef($test->i); foreach ($test as &$prop); ?>

However, readonly features do not prohibit the possibility of inner modification. Objects (or resources) whose properties are set to readonly can nonetheless be updated internally:

 > $test = new Test(new stdClass); // Legal interior mutation. $test->obj->bar = 1; // Illegal reassignment. $test->obj = new stdClass; ?>

Summary

In summary, we have learned about the PHP Class Variable through examples. I hope you can now apply this information to your PHP project apps.

Lastly, if you want to learn more about PHP Class Variable, please leave a comment below. We’ll be happy to hear it!

Leave a Comment Cancel reply

You must be logged in to post a comment.

Источник

Читайте также:  Где нужна многопоточность java
Оцените статью