- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Objects.
Definition and Usage
In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.
Primary (scalar) variables, arrays and other objects can be cast to object data type using casting operator. PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting.
Syntax
To declare an object of a class we need to use new statement
class myclass { .. .. } $obj=new myclass;
Example
<?php class SayHello{ function hello(){ echo "Hello World"; } } $obj=new SayHello; $obj->hello(); ?>
Output
This will produce following result −
Hello World
Object of stdClass is null to begin with. We can add properties dynamically
Example
<?php $obj=new stdClass; $obj->name="Deepak"; $obj->age=21; $obj->marks=75; print_r($obj); ?>
Output
This will produce following result −
stdClass Object( [name] => Deepak [age] => 21 [marks] => 75 )
Array can be typecast to object as follows
Example
<?php $arr=array("name"=>"Deepak", "age"=>21, "marks"=>75); $obj=(object)$arr; print_r($obj); ?>
Output
This will produce following result −
stdClass Object( [name] => Deepak [age] => 21 [marks] => 75 )
Conversely, an object can be cast to array
Example
<?php $obj=new stdClass; $obj->name="Deepak"; $obj->age=21; $obj->marks=75; $arr=(array)$obj; print_r($arr); ?>
Output
This will produce following result −
Array( [name] => Deepak [age] => 21 [marks] => 75 )
Variable of any scalar type can also be converted to an object by type casting. Value of scalar variable becomes value of object's scalar property.
Example
<?php $name="Deepak"; $age=21; $percent=75.50; $obj1=(object)$name; print_r($obj1); $obj2=(object)$age; print_r($obj2); $obj3=(object)$percent; print_r($obj3); ?>
Output
This will produce following result −
stdClass Object( [scalar] => Deepak ) stdClass Object( [scalar] => 21 ) stdClass Object( [scalar] => 75.5 )