Access class properties php

Access class properties php

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.

Читайте также:  Link html to external javascript

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.

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 Class properties

Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP. Value of property can be different for each instance of class. That’s why it is sometimes referred as instance variable.

Inside any instance method, property can be accessed by calling object’s context available as a pesudo-variable $this. If a property is declared as public, it is available to object with the help of -> operator. If a property is defined with static keyword, its value is shared among all objects of the class and is accessed using scope resolution operator (::) and name of class.

property declaration and access

This example shows how a property is defined and accessed

Example

fname
"; echo "$this->mname
"; echo myclass::$lname; > > $obj=new myclass(); $obj->dispdata(); ?>

Output

The output of above code is as follows −

Outside class, instance properties declared as public are available to object, but private properties are not accessible. In previous versions of PHP, var keyword was available for property declaration. Though it has now been deprecated, it is still available for backward compatibility and is treated as public declaration of property.

PHP 7.4 introduces type declaration of property variables

Example

name=$x; $this->age=$y; > > $obj=new myclass("Kiran",20); ?>

Источник

Classes and Objects in PHP Examples

Any complex application can be developed in a more manageable and maintainable way by using object-oriented programming (OOP). It is more efficient than procedural programming for developing large and complicated applications. In this programming, all variables and functions are defined as a group by using class and the instance of a class is called an object that is used to access the properties of the class. This tutorial shows the basics of object-oriented programming with the uses of class and object.

Class:

Each class contains the required variables and functions to define the properties of a particular group. Generally, the name of the class is defined by starting with the capital letter and in the singular form. The keyword, the class is used to declare a class.

Objects:

The object is declared to use the properties of a class. The object variable is declared by using the new keyword followed by the class name. Multiple object variables can be declared for a class. The object variables are work as a reference variable. So, if the property value of any class is modified by one object then the property value of another object of the same class will be changed at a time.

Example-1: Declare and read class properties

The following example shows the way to declare and access the properties of a class. Create a PHP file with the following script. Two properties named $name and $price of the class named Product are declared and initialized with the values. Next, an object of this class is declared to print the values of the properties as an object and print each property value separately.

//Print all object properties

//Print each property separately

echo «
Product Name: » . $obj_pro -> name . «
» ;

echo «Product Price: » . $obj_pro -> price . «
» ;

The following output will appear after running the above script from the server.

Example-2: Declare a class with properties and method

The following example shows the way to declare the property and method in a class. Create a PHP file with the following script. $name, $type and $price have declared as properties of the class named Product. A function named details() has been declared as the method of the class that will print the property values of the class. Next, an object of this class has declared and called the method, details().

public $name = «HP Pavillion» ;

//Declare method to print the properties

echo «Name :» . $this -> name . «
» . «Type :» . $this -> type . «
» . «Price :$» . $this -> price . «
» ;

The following output will appear after running the above script from the server.

Example-3: Declare a class with properties and method with an argument

The following example shows the use of the property and the method with an argument in a class. Create a PHP file with the following script. Three property values named $name, $type, and $price have been declared and initialized with the values. A function named total_price() has been declared with an argument named $qty as the argument. total_price() will calculate the total price of the product based on the argument value and return it to the caller. Here, $this variable is used to read the value of the class property, $price. Next, an object variable named $object has been declared to access the property and method of the class. $quantity variable has been used in the script to pass the argument value to total_price(). All property values and the return value of the function will be printed by using an object variable.

public $name = «HP Pavillion» ;

/*Declare method with argument to calculate

the total price and return*/

public function total_price ( $qty )

//Calculate the total price

$total_price = $object -> total_price ( $quantity ) ;

//Print the product details with total price

echo «Name : » . $object -> name . «
» .

«Únit Price : $» . $object -> price . «
» .

«Total Price : $» . $total_price ;

The following output will appear after running the above script from the server.

Example-4: Initialize the class properties outside the class

In the previous examples, all property values are initialized inside the class. The following example shows how the class properties will be initialized by using the object of the class. Create a PHP file with the following script. Here, three class properties have been defined inside the class without initialization. Next, an object variable is used to initialize the class properties and print property values.

//Declare properties without values

//Initialize the property values

$object -> name = «Samsung Printer M06753» ;

//Print the property values

echo «Name :» . $object -> name . «
» . «Type :» . $object -> type . «
» . «Price :$» . $object -> price . «
» ;

The following output will appear after running the above script from the server.

Video Tutorial

Conclusion:

Class and object are the basic part of object-oriented programming. The concept of the class property and the method are to be cleared to learn object-oriented programming. The basic concept of the class and object have explained in this tutorial. How the property and the method with argument are declared in a class, how the property value can be initialized inside and outside the class and how the object variable can be used to access the property and method of the class have shown here by using different examples.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

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