PHP object Type Casting In Hindi | PHP object In Hindi

Other Blogs

Blogs ❯❯ PHP

object Type Casting In PHP

Image could not load

PHP object In Hindi

बैसे तो आपने normal data types जैसे int , string , boolean etc को एक दुसरे में type cast किया होगा , लेकिन आज हम इस article में PHP में object type casting के बारे में बात करेंगे।

PHP में किसी दूसरे data type को object बनाने के लिए object keyword का ही use किया जाता है।

For Example

$x = 10; $obj = (object) $x;

PHP object type Casting Example

अब जैसा कि आपको पता है कि किसी भी Object में properties होती हैं लेकिन primitive values (like : int, bool, string etc.) तो normal value हैं इनमे कोई property तो है नहीं , तो जब हम primitive values को object में type cast करते हैं तो object में एक default property scalar होती है।

यही scalar property हमारी actual primitive value को contain करती है।

<?php $x = "Hello Object !"; $obj = (object)$x; var_dump($obj); // you can access the actual value using scalar property. echo $obj->scalar; ?>

Output

object(stdClass)#1 (1) {
  ["scalar"]=>
  string(14) "Hello Object !"
}
Hello Object !

PHP Type Cast Array to object

हालाँकि अगर आप किसी Array को object में convert करेंगे तो आपको properties ही मिलेंगी जिनकी values को आप array key के according access कर सकते हैं।

<?php $x = [ "name" => "Babu Rao", "age" => "60", ]; $obj = (object) $x; var_dump($obj); // you can access the actual value using array key name. echo "Name : $obj->name \n"; echo "Age : $obj->age"; ?>

Output

object(stdClass)#1 (2) {
  ["name"]=>
  string(8) "Babu Rao"
  ["age"]=>
  string(2) "60"
}

Name : Babu Rao 
Age : 60

ऊपर दिया गया example तो Associative Array के लिए था , Indexed Array के case में सभी index , property की तरह work करेंगी।

Example

<?php $persons = ["Raju", "Shyam", "Babu Rao"]; $obj = (object) $persons; var_dump($obj); // you can access the actual value using array key name. echo "Person 1 : ". $obj->{"0"}; echo "Person 2 : ". $obj->{"1"}; echo "Person 3 : ". $obj->{"2"}; ?>
object(stdClass)#1 (3) {
  ["0"]=>
  string(4) "Raju"
  ["1"]=>
  string(5) "Shyam"
  ["2"]=>
  string(8) "Babu Rao"
}
Person 1 : Raju
Person 2 : Shyam
Person 3 : Babu Rao

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 5.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook

Your Thought ?

Please wait . . .

    Recent Blogs

    Loading ...

    0 Comment(s) found !