Returning objects in php

I see similar questions, but I seem to have a problem with more basic materials than requested. How to declare a variable in php? My problem is that I have a function that reads the database table and returns a record (only one) as an object.

class User{ public $uid; public $name; public $status; } function GetUserInfo($uid) { // Query DB $userObj = new User(); // convert the result into the User object. var_dump($userObj); return $userObj; } // In another file I call the above function. .... $newuser = GetUserInfo($uid); var_dump($newuser); 

What is the problem, I can not understand. Essentially, var_dump() in the GetUserInfo() function works fine. The appearance of var_dump() after calling GetUserInfo() does not work.

+4
source share
3 answers

Using PHP5 works:

 <pre> <?php class User{ public $uid; public $name; public $status; } function GetUserInfo($uid) { $userObj = new User(); $userObj->uid=$uid; $userObj->name='zaf'; $userObj->status='guru'; return $userObj; } $newuser = GetUserInfo(1); var_dump($newuser); ?> </pre> object(User)#1 (3) { ["uid"]=> int(1) ["name"]=> string(3) "zaf" ["status"]=> string(4) "guru" } 
+6
source

First create a new instance of the User class. Then use this instance to call your function and provide the $ uid parameter to make your request run like shoudl. If there is a match in your datatable, your Userobject will be populated with DB results.

Personally, I prefer to use static calls, which makes your code more readable and compact.

Difference:

 $userObj = new User(); $user = $userObj->GetUserInfo('your uid'); 

or

 $user = User::GetUserInfo('your uid'); 

And I see a strange } on line 4. Correct me if I am wrong, but I think it should be after } from the GetUserInfo($uid) function.

0
source

I ran into the same problem. However, I am using 5.6.1. Here is what I did wrong:

 class component { public function myFunc() { $obj = new SomeComp(); try { do some work return $obj; } finally { $obj = null; } } 

Everything in the class method worked fine, $ obj had information when returning. However, the following results were set to zero:

 $myClass = new component(); $myObj = $myClass->myFunc(); var_dump($myObj); // returns NULL 

Setting $ obj = null; in the class method try ... finally destroy $ obj by making $ myObj NULL. Deleted $ obj = null; and the method returns the correct information.

0
source

Source: https://habr.com/ru/post/1308779/


All Articles