Accessing Methods and Properties Using the $this Variable in PHP


Accessing Methods and Properties Using the $this Variable:

During the execution of an object's method, a special variable called $this is automatically defined, which denotes a reference to the object itself. By using this variable and the -> notation, the object's methods and properties can be further referenced. For example, you can access the $name property by using $this->name (note that you don't use a $ before the name of the property). An object's methods can be accessed in the same way; for example, from inside one of person's methods, you could call getName() by writing $this->getName().

Class Constants.Cloning Objects, Polymorphism:

Class constants:

A constant is, just like the name implies, a variable that can never be changed. When you declare a constant, you assign a value to it, and after that, the value will never change. Normally, simple variables are just easier to use, but in certain cases constants are preferable, for instance to signal to other programmers (or your self, in case you forget) that this specific value should not be changed during runtime.

Class constants are just like regular constants, except for the fact that they are declared on a class and therefore also accessed through this specific class. Just like with static members, you use the double-colon operator to access a class constant. Here is a basic example:

<?php

class User

{

   const DefaultUsername = "John Doe";

   const MinimumPasswordLength = 6;

}

echo "The default username is " . User::DefaultUsername;

echo "The minimum password length is " . User::MinimumPasswordLength;

?>

Output: The default username is John Doe
The minimum password length is 6-CLASS CONSTANTS

Custom Search

%d bloggers like this: