Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

php - Why can't I access the array with index directly?

I got confused when I was trying to access an array element directly with its index. I guess I could explain it better in coding:-

I am having an object of Employee Class and I TypeCast it to array and tried to display it like this:

$arrOfObj = (array) $objEmployee;

$arrKeys = array_keys( $arrOfObj );

display( $arrOfObj ); // display() is a method in my library that prints an array in a mannered way.

this gives me the following output :-

Array
(
   [*m_UserId] => 1155
   [*m_EmailPassword] => 
   [*m_IsAssignedToManagementCompany] => 
   [*m_ManagementCompanyId] => 
   [*m_DepartmentId] => 3
   [*m_DesignationId] => 4
   [*m_EmployeeCompletedMonth] => 
   [*m_EmployeeCompletedDay] => 
   [*m_EmailAddress] =>showket.mca@gmail.com
   ------
   ------
 )

Now here I dont understand this Star(*). when my member variables are simple like m_UserId, m_EmialPassword and So on where from it gets this Star. and when I try to display the same with following 2 statements I got an error :-

display( $arrOfObj['*m_EmailAddress'] );

or

display( $arrOfObj['m_EmailAddress'] );

Both give the Error message Undefined index: m_EmailAddress

And when i try to do it this way It works fine :-

display( $arrOfObj[$arrKeys[8]] );

The last one works fine, Can anyone explain me the problem.

            display( $arrOfObj[$arrKeys[11]] );
            display( $arrOfObj['m_strEmailAddress'] );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

http://php.net/manual/en/language.types.array.php#language.types.array.casting

Try var_dump(bin2hex($arrKeys[8])) for enlightenment. Also see the example in the above linked manual.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...