Javascript (Node.js) in PHP - php

Is there any project like PHP.js but in vice direction to provide PHP implementation of JS classes and functions? In particular Date, RegEx, String classes?
I found this class for String but I am looking for a more complete collection.
My consern is not about using or not using such thing, I just need such thing.

Today I found jsphp. It seems promising.
JavaScript for PHP (jsphp) is a pseudo-implementation of the ECMA 262
standard (JavaScript 8.5.1) for PHP 5.3+. It allows you to write code
in PHP as if it were JavaScript, using the standard API and the
dynamic attributes available in the language, such as prototype
inheritence and chaining, first-class functions, and other
object-orientated features. It includes JSBoolean, JSNumber, JSString,
JSObject, JSArray, JSFunction, JSRegExp, JSDate, JSError and JSMath,
as well as the global helper functions, such as parseInt or isNaN.
The syntax in jsphp is very similar to a native implementation, although adapted to the syntax of PHP. For example, the variables are
prepended by a "$", the Object access opertaor is "->", and Strings
are concatenated using a ".".
$myString = new JSString( 'Hello World' );
$myString = $myString->split( '' )->reverse()->join( '' );
print( 'Reversed: ' . $myString ); // dlroW olleH

There is not - and there can not be - somehting like you ask for.
Javascript has a special syntax for regular expressions, something PHP could not take.
Similar how "object" methods in javascript are invoked. And the scope of variables is different. So this would not work.
Instead use the PHP functions. If they are not complete or useable enough for you, wrap them into objects so you can create an interface you like. Or use one of the many libraries that are available.

Related

Call function on string literal

I am wondering whether it is possible to call functions on string literals (Like in Python) in PHP (Tried googling, but 90% sure my terminology is off).
Example python:
"test,1,2,3".split()
I want to achieve something like (In php psuedo code):
$result = "SELECT `db`.`table`.`field` FROM `db`.`table` WHERE 1"->query();
Currently I am doing this:
$result = MySql::query("SELECT `db`.`table`.`field` FROM `db`.`table` WHERE 1");
But I really like the simplicity of the middle example and was wondering if anything like that is possible in PHP, maybe by overriding the PHP string class?
The difference is that everything in Python (and similar OO languages) is an object, that's why even strings have "methods" and "properties". PHP isn't a full top-to-bottom OO language, strings are just primitive strings. Even if they were objects, a string probably wouldn't have methods pertaining to database queries, because that'd be quite weird OO design with terribly mixed responsibilities.
There's no real way to do what you're talking about
$result = "SELECT `db`.`table`.`field` FROM `db`.`table` WHERE 1"->query();
In this example, your string is just a string. You then try to reference it like an object. In this case, you would get a Fatal error because you're telling PHP to use an object where none exists.
The closest thing to what you describe is direct chaining, where you create an instance of the class and reference it in the same statement (available in PHP >= 5.4)
$class = (new Class())->function();

Creating custom PHP Syntax Parser

I am thinking about how one would go about creating a PHP equivalent for a couple of libraries I found for CSS and JS.
One is Less CSS which is a dynamic stylesheet language. The basic idea behind Less CSS is that it allows you to create more dynamic CSS rules containing entities that "regular" CSS does not support such as mixins, functions etc and then the final Less CSS compiles those syntax into regular CSS.
Another interesting JS library which behaves in a (kind of) similar pattern is CoffeeScript where you can write "tidier & simpler" code which then gets compiled into regular Javascript.
How would one go about creating a simple similar interface for PHP? Just as a proof of concept; I am only trying to learn stuff. Lets just take a simple use case of extending classes.
class a
{
function a_test()
{
echo "This is test in a ";
}
}
class b extends a
{
function b_test()
{
parent::a_test();
echo "This is test in b";
}
}
$b = new b();
$b->b_test();
Suppose I want to let the user write class b as (just for the example):
class b[a] //would mean b extends a
{
function b_test()
{
[a_test] //would mean parent::a_test()
echo "This is test in b";
}
}
And let them later have that code "resolve" to regular PHP (Usually by running a separate command/process I would believe). My question is how would I go about creating something like this. Can it be done in PHP, would I require to use something like C/C++. How should I approach this problem if I were to go at it? Are there any resources online? Any pointers are deeply appreciated!
Language transcoders are not as easy as one might think.
The example you gave can be implemented very easily with a preg_replace that looks for class definitions and replaces [a] with extends a.
But more complex features need a transcoder which is a suite of smaller logical pieces of code.
In most programmer jargon people incorrectly call transcoders compilers but the difference between compilers and transcoders is that compilers read source code and output raw binary machine code while transcoders read source code and output (a different) source code.
The PHP (or JavaScript) runtime for example is neither compiler nor transcoder, it's an interpreter.
But enough about jargon let's talk about transcoders:
To build a transcoder you must first build a tokenizer, it breaks apart the source code into tokens, meaning that if it sees an entire word such as 'class' or the name of a class or 'function' or the name of a function, it captures that word and considers it a token. When it encounters another token such as an opening round bracket or an opening brace or a square bracket etc. it considers that another token.
Luckily all of the recognized tokens available in PHP are already easily scanned by token_get_all which is a function PHP is bundled with. You may have some trouble because PHP assumes some things about how you use symbols but all in all you can make use of this function.
The tokenizer creates a flat list of all the tokens it finds and gives it to the parser.
The parser is the second phase of your transcoder, it reads the list of tokens and decides stuff like "if token[0] is a class and token[1] is a name_value then we have a class" etc.. after running through the entire list of tokens we should have an abstract syntax tree.
The abstract syntax tree is a structure that symbolically retains only the relevant information about a the source code.
$ast = array(
'my_derived_class' => array(
'implements' => array(
'my_interface_1',
'my_interface_2',
'my_interface_3'),
'extends' => 'my_base_class',
'members' => array(
'my_property_name' => 'my_default_value',
'my_method_name' => array( /* ... */ )
)
)
);
After you get an abstract syntax tree you need to walk through it and output the destination source code.
The real tricky part is the parser which (depending on the complexity of the language you are parsing) may need a backtracking algorithm or some other form of pattern matching to differentiate similar cases against one another.
I recommend reading about this in Terence Parr' book http://pragprog.com/book/tpdsl/language-implementation-patterns which describes in detail the design patterns needed to write a transcoder.
In Terrence' book you'll find out why some languages such as HTML or CSS are much simpler (structurally) than PHP or JavaScript and how that relates the complexity of the language parser.

Smarty: how to use PHP functions?

Say I have the following in my TPL file:
{$a}
and I want to apply certain PHP native functions (e.g. strip_tags) to that Smarty variable. Is this possible within the TPL? If so, how?
You can use any php function in a smarty template in the following way:
{$a|php_function_name}
or
{$a|php_function_name:param2:param3:...}
In the second example you can specify additional parameters for the php function (the first is always $a in our case).
for example:
{$a|substr:4:3} should result something like substr($_tpl_vars['a'],4,3); when smarty compiles it.
The best way is probably to create your own plugins and modifiers for Smarty. For your specific example, Smarty already has a strip_tags modifier. Use it like this:
{$a|strip_tags}
Very good question, it took me a while to completely figure this one out.
Call a function, passing a single parameter:
{"this is my string"|strtoupper}
// same as:
strtoupper("this is my string")
{$a:strtoupper}
// same as:
strtoupper($a)
Call a function, passing multiple parameters
{"/"|str_replace:"-":"this is my string"}
// same as:
str_replace("/", "-", "this is my string")
{"/"|str_replace:"-":$a}
// same as:
str_replace("/", "-", $a)
Or you can use this: (call function directly)
{rand()}
The whole point of templating systems is to abstract the creation of views from the underlying language. In other words, your variables should be prepared for displaying before they are passed to a templating engine, and you should not use any PHP functions in the template itself.
Smarty already has a Language Modifier built in for this.
{$a|strip_tags}
You don't need Native functions as there already integrated into the plugin system
http://www.smarty.net/docsv2/en/language.modifier.strip.tags.tpl
others here:
http://www.smarty.net/docsv2/en/language.modifiers.tpl

php e() and h() functions?

I and lately I'm seeing h() and e() functions in PHP. I have googled them, but they are so short that results don't give any idea of what they are. I got results like exponential or math related functions. For example:
<td><?php echo h($room['Room']['message']) ?></td>
Does anyone have an idea? or maybe they are not called functions? (I think I read about that very long ago, but I can remember its real name)
ADDED:
Thanks, for the replies. I am using CakePHP and also found an e() example:
<?php e($time->niceShort($question['Question'] ['created'])) ?>
If they were escaping somehow strings I think it would make sense, since I always see them right next the "echo"
I still don't know what they are ;(
As several readers have said, these are CakePHP-specific short-cuts. You can find them in the API docs at: here (for CakePHP 2.x)
I think I read that some of these are going to be removed in 1.3, personally I never used e() as typing echo really doesn't take that much longer :)
edit: e() is deprecated in 1.3 and no longer available in 2.0 see here
It looks like it might be CakePHP.
See e()
e (mixed $data)
Convenience wrapper for echo().
This has been Deprecated and will be removed in 2.0 version. Use
echo() instead.
See h()
h (string $text, string $charset = null)
Convenience wrapper for htmlspecialchars().
Most likely, they are dummy functions someone introduced for the sake of brevity. The h(), for example, looks like an alias for htmlspecialchars():
function h($s)
{
return htmlspecialchars($s);
}
So look for them in the include files. Espec. the ones with names likes "util.php" or "lib.php".
Likely the framework you're using is doing some escaping and has defined some short hands for htmlentities and htmlspecialchars or equivalents.
I'd do a search on whatever framework you're using for "function h("
They are probably functions defined and implemented by the group's code that you're looking at. I'm not aware of any e/h functions in the PHP language.
Nothing here:
http://us3.php.net/manual/en/function.h.php
http://us3.php.net/manual/en/function.e.php
There aren't any functions in PHP called h() and e(). They must be declared in the project you are working on. search for them and find out what they do.
In CakePHP h() is:
Convenience wrapper for htmlspecialchars()
For more information about Global constants and functions in CakePHP view this link
http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html
I'd guess that h() escapes user-submitted data for safe output, and e() escapes for database insertion. Whatever the functionality, these are not stock PHP functions.
It's CakePHP.
echo h('some stuff')
Is just htmlspecialchar()ing the stuff.
If you are using a decent editor press ctrl and click on the function. It should take you to the function's declaration.
http://book.cakephp.org/view/121/Global-Functions these are shortcut functions in cakePHP
Many of them are deprecated in 1.3 so beware of using them yourself
h() is global function in CakePHP. Documents about h() for CakePHP version 2.5.7 : http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#global-functions
Laravel also use e() helper function to runs htmlentities over the given string.
echo e('<html>foo</html>');
// <html>foo</html>
documentation : https://laravel.com/docs/5.8/helpers#method-e

PHP's create_function() versus just using eval()

In PHP you have the create_function() function which creates a unique named lambda function like this:
$myFunction = create_function('$foo', 'return $foo;');
$myFunction('bar'); //Returns bar
Is this actually any better (apart from being more easy) then just doing:
do{
$myFunction = 'createdFunction_'.rand();
}
while(function_exists($myFunction));
eval("function $myFunction(\$foo) { return \$foo; }");
$myFunction('bar'); //Returns bar
Is create_function really better? (apart from the fact that it is more easy)
Using eval() will clutter the global function list, create_function() will not, apart from that there's no big difference. However, both methods require writing the function body inside a PHP string which is error-prone and if you were working on my project I would order you to just declare a helper function using the normal syntax.
Anonymous functions in PHP are so poorly implemented that your code is actually better off not using them. (Thankfully this will be fixed in PHP 5.3).
On my understanding of the relevant docs,[1] they both do the same thing, create_function() just comes up with a unique function name for you.
To address some other comments on this question:
create_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is only useful for the given scope.
It may well be that eval() runs in the current scope, but function definitions get dumped into the global namespace anyway.[2] So whenever you define a function, it will be accessible everywhere else in your program.
Using eval() will clutter the global function list, create_function() will not
create_function() only returns a string with the name of the new function,[3] not some special callback type. So, both techniques will pollute your global namespace.
So no, apart from create_function() being easier, it does not appear to be any better than eval().
Footnotes:
[1] http://au2.php.net/manual/en/functions.user-defined.php ; http://au.php.net/create_function ; http://au.php.net/eval
[2] http://au2.php.net/manual/en/functions.user-defined.php
[3] http://au.php.net/create_function
Personally, I've found that create_function() is extremely handy when sorting arrays.
In fact, I just searched the web, and it seems that the PHP documentation has a good example of this.
http://us.php.net/create_function
Scroll down to Example #3 Using anonymous functions as callback functions.
create_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is only useful for the given scope.
(apart from the fact that it is more easy)
I don't understand how you can dismiss this so readily. Given your two examples, which is easier to understand at a glance? Create_function tells you what you intend to accomplish. Eval doesn't.

Categories