0

I have a PHP array of objects that have a function, getValue which gets the object's value. So, if i want to get it's value in PHP i just:

echo mapArray[2][2]->getValue;

I passed the array to JS using:

var mapArray = <?php echo json_encode($mapArray); ?>

If i do a

document.write(mapArray);

i get a whole array of "object Object" strings. If i try:

document.write(mapArray.[2][2].getValue);

i get "undefined".

Why this happens? Do i have to mimic PHP data object so the methods are recognised in JS or the JSON encoding can give me a hand with this?

2
  • What is the rendered result of your second code block? The one with the PHP bit in it? Commented Dec 4, 2010 at 19:36
  • I assume in your first block of code you meant mapArray[2][2]->getValue(). If getValue is a simple property, and not a method, the rest of the question doesn't make sense. Commented Dec 4, 2010 at 19:48

2 Answers 2

4

All json_encode does is return a string representing your data.

Imagine what it would take to be able to create JavaScript versions of all your PHP functions. json_encode would essentially have to be a compiler, able to understand all possible PHP functionality and convert it to equivalent JavaScript functionality.

It's possible to imagine such a thing working for simple functions, but how could it work for more elaborate code? If your getValue function invokes some of your library PHP code to make a MySQL connection, retrieve data, and perform calculations using built-in PHP functions that don't exist in JavaScript, the poor json_encode function would have to essentially convert the entire PHP language into JavaScript.

No, all you can get in JSON is data. Not functionality.

For the specific case you've described, where you have some private data with an accessor method, just create an array (or object) that describes the actual data you want returned to the browser before calling json_encode.

Sign up to request clarification or add additional context in comments.

Comments

0

When you serialize the array to JSON and pass it to the client for evaluation with JavaScript you can only pass the representation of the array and it's contents (i.e. property values).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.