Skip to content

Commit 7f1fc79

Browse files
committed
Implement __toString for JsObject
1 parent c083085 commit 7f1fc79

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/node_php_jsobject_class.cc

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,14 @@ PHP_METHOD(JsObject, __invoke) {
367367
TRACE("<");
368368
}
369369

370+
// Implement `__toString` by calling JS `toString` method.
371+
PHP_METHOD(JsObject, __toString) {
372+
// use plain zval to avoid allocating copy of method name
373+
zval method; ZVAL_STRINGL(&method, "toString", 8, 0);
374+
zval *args = NULL;
375+
call_user_function(EG(function_table), &this_ptr, &method,
376+
return_value, 0, &args TSRMLS_CC);
377+
}
370378

371379
/* Use (slightly thunked) versions of the has/read/write property handlers
372380
* for dimensions as well, so that $obj['foo'] acts like $obj->foo. */
@@ -499,6 +507,8 @@ ZEND_BEGIN_ARG_INFO_EX(node_php_jsobject_call_args, 0, 1/*return by ref*/, 1)
499507
ZEND_ARG_INFO(0, member)
500508
ZEND_ARG_INFO(0, args)
501509
ZEND_END_ARG_INFO()
510+
ZEND_BEGIN_ARG_INFO_EX(node_php_jsobject_toString_args, 0, 0, 0)
511+
ZEND_END_ARG_INFO()
502512

503513
static const zend_function_entry node_php_jsobject_methods[] = {
504514
PHP_ME(JsObject, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
@@ -512,6 +522,7 @@ static const zend_function_entry node_php_jsobject_methods[] = {
512522
PHP_ME(JsObject, __unset, node_php_jsobject_unset_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
513523
PHP_ME(JsObject, __call, node_php_jsobject_call_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
514524
PHP_ME(JsObject, __invoke, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
525+
PHP_ME(JsObject, __toString, node_php_jsobject_toString_args, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
515526
ZEND_FE_END
516527
};
517528

test/context.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,4 +249,29 @@ describe('Passing context object from JS to PHP', function() {
249249
);
250250
});
251251
});
252+
it('should implement __toString', function() {
253+
var out = new StringStream();
254+
var A = function A(v) { this.f = v; };
255+
A.prototype.toString = function() { return JSON.stringify(this.f); };
256+
var context = { a: new A(32), b: {} };
257+
return php.request({
258+
source: [
259+
"call_user_func(function () {",
260+
" $c = $_SERVER['CONTEXT'];",
261+
" echo 'a is ' . $c->a . '\n';",
262+
" echo 'b is ' . $c->b . '\n';",
263+
" $c->a->f = 'abc';",
264+
" echo 'a is ' . $c->a . '\n';",
265+
"})"].join('\n'),
266+
stream: out,
267+
context: context
268+
}).then(function() {
269+
out.toString().should.equal([
270+
'a is 32',
271+
'b is [object Object]',
272+
'a is "abc"',
273+
''
274+
].join('\n'));
275+
});
276+
});
252277
});

0 commit comments

Comments
 (0)