PHP's is_callable in JavaScript
How to use
You you can install via yarn add locutus
and
require this function via const is_callable = require('locutus/php/var/is_callable')
.
It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.
Examples
Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.
# | code | expected result |
---|---|---|
1 | is_callable('is_callable') | true |
2 | is_callable('bogusFunction', true) | true // gives true because does not do strict checking |
3 | function SomeClass () {}
SomeClass.prototype.someMethod = function (){}
var testObj = new SomeClass()
is_callable([testObj, 'someMethod'], true, 'myVar')
var $result = myVar | 'SomeClass::someMethod' |
4 | is_callable(function () {}) | true |
5 | is_callable(class MyClass {}) | false |
Notes
The variable callableName cannot work as a string variable passed by reference as in PHP (since JavaScript does not support passing strings by reference), but instead will take the name of a global variable and set that instead. When used on an object, depends on a constructor property being kept on the object prototype
Depending on the
callableName
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.
Here’s what our current JavaScript equivalent to PHP's is_callable looks like.
module.exports = function is_callable(mixedVar, syntaxOnly, callableName) { |
A community effort
Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows
The McDonald’s Theory.
This means that we assimilate first iterations with imperfections,
hoping for others to take issue with-and improve them.
This unorthodox approach has worked very well to foster fun and fruitful collaboration,
but please be reminded to use our creations at your own risk.
THE SOFTWARE IS PROVIDED "AS IS"
has never been more true than for Locutus.
Now go and: [ View on GitHub | Edit on GitHub | View Raw ]
Star