
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP Basics of Class and Object
Introduction
Class is a user defined data type in PHP. In order to define a new class, PHP provides a keyword class, which is followed by a name. Any label that is valid as per PHP's naming convention (excluding PHP's reserved words) can be used as name of class. Constituents of class are defined in curly bracket that follows name of class
Syntax
class myclass{ // }
Class may contain constants, variables or properties and methods - which are similar to functions
Example of class
This example shows how a Class is defined
Example
<?php class myclass{ const MYCONSTANT=100; public $var1="Hello"; function dispvar(){ echo $this->var1; } } ?>
Function defined inside class is called method. Calling object's context is available inside a method with a pseudo-variable $this. If method is defined as static, it is accessed with name of class. Calling a non-static method statically has been deprecated in PHP 7
The new operator declares a new object of given class. ame of class followed by paentheses should be mentioned in front of new keyword. An uninitialized object (or with default values to properties) is created if there are no arguments inside parentheses. If class provides definition of constructor with parameters, matching number of arguments must be given. Class must be defined before creating instance (or object)
Example
<?php class myclass{ const MYCONSTANT=100; public $var1="Hello"; function dispvar(){ echo $this->var1; } } $obj=new myclass(); $obj->dispvar(); ?>
Output
This will produce following result. −
Hello
- Related Articles
- PHP Variable Basics
- PHP Inherit the properties of non-class object?
- Check whether property exists in object or class with PHP
- Basics of NS2 and Otcltcl script
- Object and class in Java
- Basics of React.js Routing
- The Basics of Gastroparesis
- PHP Class Abstraction
- PHP Class Constants
- PHP Class properties
- PHP Closure class
- PHP Generator class
- PHP WeakReference class
- Microcomputer Basics
- Microprocessor Basics
