PHP's call_user_func in TypeScript

How to use

Install via yarn add locutus and import: import { call_user_func } from 'locutus/php/funchand/call_user_func'.

Or with CommonJS: const { call_user_func } = require('locutus/php/funchand/call_user_func')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1call_user_func('isNaN', 'a')true

Notes

  • Depends on call_user_func_array which in turn depends on the cb that is passed, this function can use eval. The eval input is however checked to only allow valid function names, So it should not be unsafer than uses without eval (seeing as you can) already pass any function to be executed here.

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's call_user_func looks like.

import type { PhpCallableArgs, PhpCallableDescriptor, PhpRuntimeValue } from '../_helpers/_phpTypes.ts'
import { call_user_func_array as callUserFuncArray } from '../funchand/call_user_func_array.ts'

type FunctionArg = PhpRuntimeValue

export function call_user_func<TResult = FunctionArg, TArgs extends PhpCallableArgs = PhpCallableArgs>(
cb: PhpCallableDescriptor<TArgs, TResult>,
...parameters: TArgs
): TResult {
// discuss at: https://locutus.io/php/call_user_func/
// original by: Brett Zamir (https://brett-zamir.me)
// improved by: Diplom@t (https://difane.com/)
// improved by: Brett Zamir (https://brett-zamir.me)
// note 1: Depends on call_user_func_array which in turn depends on the `cb` that is passed,
// note 1: this function can use `eval`.
// note 1: The `eval` input is however checked to only allow valid function names,
// note 1: So it should not be unsafer than uses without eval (seeing as you can)
// note 1: already pass any function to be executed here.
// example 1: call_user_func('isNaN', 'a')
// returns 1: true

return callUserFuncArray<TResult, TArgs>(cb, parameters)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP funchand functions


Star