Does PHP interpret code in the same way that JavaScript does? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Does PHP interpret code in the same way that JavaScript does? Upon some research, I've gathered that JavaScript programs are run in a so-called 'two-pass' read. The first run gets the syntax and function definitions of the program. ('Parses' the data so to speak), and the second run - well - runs the data. Does PHP work the same way? If not, how does PHP interpret code?
What are the general functions of a PHP interpreter?

Most programming languages work that way, maybe save for batch files. The source code is parsed into tokens and a syntax tree is created which is then evaluated. These are three separate steps and it's practically a lot simpler to keep them separated. If you'd want to mush them together so code got executed while it is being parsed, that means the parser would have to read just enough to get one full block of something which is executable, then hand that over to the runtime, which would then have to hand control back to the parser. It's a lot easier to do everything one by one.

What you've described in the question is a very tiny aspect of how the interpreter works.
PHP does indeed do this: you can tell because it is valid to have a function call higher up in the code than the actual definition of the function that is being called.
<?php
myFunction(); //this is only valid here before the function itself because of two-pass parsing.
function myFunction() {
.....
}
myFunction(); //in a single-pass system, the function call would have to be here, after the function itself.
?>
If you only had one pass, you would only be able to call a function after the function itself had been defined. Some languages do work this way (C and Pascal are good examples). These languages require the use of header files if you want write a function call earlier in the code than the function itself is defined.
The difference is that those languages are compiled, which means that the code is only actually run once everything has been built into an executable. The single-pass approach with header files wouldn't work in an interpreted environment because while the header may allow the compiler to accept the function call as valid, an interpeter would still fail because it simply wouldn't have the function available to call.
For this reason, pretty much any interpreted language is going to use this two-pass mechanism.
However, as I said, this is just a small part of the overall design of an interpreter.

Related

Create a global library in javascript, holding both state and behaviour [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to create a globally-accessible library myLib in Javascript. My library should do the following
Keep a somewhat persistent variable myLib.tax.
-- It should survive through the handling of a typical browser user event, at least in simple cases. I don't care if it survives longer than that or not.
-- external code should be able to set the value of this variable, either through a setter or otherwise.
Has a function myLib.applyTax(var price).
-- return value is price + myLib.tax.
-- I don't care what it does if either price or tax is not a number.
Lastly, a brief example of how to call this from another file, in such a way that:
-- for example, file A might set the value of the tax, then file B might apply the.
-- this works even though files A and B are unrelated.
The purpose of this question is for me to understand code and state encapsulation and how to use them from elsewhere.
EDIT: For the benefit of anyone seeing this later, what I did not understand when asking this question is that referring from javascript file A.js to javascript file B.js is a difficult problem unless that is enabled externally, for example in the html. For more detail, see How do I include a JavaScript file in another JavaScript file?
From your comments I see you would implement a Singleton Pattern in C# through static methods and data.
In Javascript you can do the same by managing the closures and putting that data into the outermost one, which would then be accessible to all code due to lexical scoping.
But I'd rather avoid singletons every day. Instead, use dependency injection as follows. This is just an example to show the technique, you'll have to code an actual solution yourself.
var lex = (function () {
var privatedata;
function privatemethod()
{
}
return {
publicmethod1: function (arg1, arg2) { ... },
publicmethod2: function (arg1, arg2) { ... },
getPublicData: function () { ... }
};
}());
This incapsulated object is then injected wherever you need it:
function consumerCode(lexicon)
{
...
}
consumerCode(lex); // injects the lex instance into the consumer code
By having only one instance and passing that same instance around wherever you need it, you will have pretty much what you were asking for.
This technique is not limited Javascript but also useful in C#. But in Javascript with loose typing it is especially powerful.

Why is separation of JavaScript and HTML a good practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have been reading about some good practices in JavaScript and one of them was Unobtrusive JavaScript. The first point caught my attention
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
On the wiki page, one of the examples is that you should bind actions to events in JS files instead of in the HTML. This example
<input type="text" name="date" id="date" />
...
window.onload = function() {
document.getElementById('date').onchange = validateDate;
};
is favored over
<input type="text" name="date" onchange="validateDate()" />
However, I would say I'd prefer the second code with onchange attribute over the first one. My reasons for this are
It is easily readable and immediately clear what will happen on change (or any other event) on that element.
I don't have to got through JavaScript files and look where (and whether) the onchange event is bind and whether there are some other events such as click defined for #date.
Frameworks such as AngularJS have ng-click and is mixing up HTML structure with JS. Why shouldn't I?
The disadvantages of not using unobtrusive javascript that I have read about are
Polluting global namespace.
Creating long and unreadable inline code.
If the code for an event changes, you have to change it only in one place - that is in a JS file.
But I think that the disadvantages can be solved.
Instead of polluting namespace, create the app in one variable so the code would look like onchange="app.validateDate()" and no polluting would happen.
Inline code would not be written and would be separated in a function in JS file, then it'd be called like onclick="app.action();".
Isn't it the same as using a function in onclick attribute? Because in the end you have to make a change just in one function in both approaches whether it is $('input').change(function () {/* ... change ... */}); or app.action = function () {/* ... change ... */}.
So is it actually still considered a good practice?
This is a very broad topic and heavily opinion based. There is no one answer to everything. However, here are some observations:
You are polluting the namespace whatever you do. app.validateDate pollutes the namespace just as validateDate does, just by virtue of needing to have a globally accessible function name. In complex modern sites, there are tons of scripts competing for global names. Ideally you're never exposing any name globally, not even a namespace name.
.onclick = handler is not great either. You'd want:
document.getElementById('date').addEventListener('change', function () { .. });
This is even less obtrusive and allows several scripts to bind event listeners to the same element. Again, in complex modern sites one of the highest priorities you can have is to ensure nobody is stepping on anyone else's feet. You never know who else might be interested in the change event of that element in the future.
It is still more code to write it inline than elsewhere. Longer HTML code that is. HTML can already be very verbose. Anything you can move elsewhere you should. Reducing the amount of code in any one particular file is an art in itself and important for readability. Yeah, it's "just one more attribute"... on top of all the other attributes and elements and inline declarations you're also not avoiding. It's just piling up, and that's how code gets messy and unreadable and unmaintainable.
Reusability: document.getElementById(..).addEventListener can be written once in an external file and automagically reused across many different pages. <.. onclick=".."> needs to be repeatedly written every single time. DRY your code.
For tiny projects it often hardly matters. But again, sites are getting more and more complex. Business needs demand constant changes. Just one more analytics script, just one more Javascript based social widget, now change it all back, now keep all the versions of dependencies in sync, now rip it all out again and redesign for our 2.0 launch next week. Do it all with 10 other people in parallel without nuking each others code on every build or needing long sessions of resolving git-merge conflicts. In such an environment, every little bit of decoupling and indirection and flexibility helps.
Since you mention Angular:
Angular avoids some of these issues by employing a completely different template parsing model. When you write onclick=foo, then you need to bind to a global function name. However, when Angular does ng-click=foo, foo is a locally scoped entity in an ng-scope. It's not a global name. Angular separates between a controller and a view, where the controller essentially exposes a specific API on the $scope object which the view can use; both the controller and the view are still interchangeable as long as the specified API contract is kept (meaning as long as the $scope object keeps the same attributes).
All ng directives are evaluated against a custom scoping and evaluation engine which does not have much to do with Javascript's default modus operandi.

Should I use eval to patch/extend a widget?

This question may be too opinion based but since avoiding eval is almost unanimously agreed upon, I'd imagine there should be objective answers.
I'd like to "patch" an existing open-source widget to avoid creating my own custom build of it. But the parts I want to patch are internal functions which are completely hidden. IE:
function dostuff(){
function iCantBeEdittedSinceImNotAPrototypeMethod_unlessDoStuffIsCompletelyOverwrittenButItsVeryLong(){
//code that needs patched
};
};
The only way I can see of doing this is to turn the function dostuff into text, search and replace iCantBeEditted and then eval it.
How bad is this use of eval?
And the specific context that I'd like to use this with is fullcalendar's compareSegs function that decides sorts the order of events.
Concerns:
safety of eval
modifying a minified file. I can find the desired function with a somewhat fail safe pattern but even if I make it variable name agnostic, this could cause problems when fullcalendar is updated.
performance. This file is 72kb after being minified.
So, should I do this? Is there an easier alternative?

How many Vars is too many in JS? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a page I am building, and our solution to a problem involved wrapping some code inside a function then calling that when required.
Now the page is growing, and each item has its own function. According to D. Crockford each function is put in a VAR anyway so:
function functionName(){}
is equivalent to:
var var1 = functionName(){}
So now we have LOTS of vars in the page (I have also written them specifically in the latter format as Mr. Crockford promotes) and I am getting worried this creates too many variables (not sure this will cause any issues, performance or otherwise). I am thinking of making a single Object Literal and adding each function as a value to a key. This I think will reduce all these vars into a single manageable unit and reduce the amount of variables I am using (and avoid any potential issues) - or will it?
Thanks!
var keyword is actually being used in order to manage variable scope.
Not using var keyword makes the variable a global one. The memory occupied by the variables are cleared when the variable isn't used anymore. Most of the modern browsers contains a garbage collector responsible for freeing up the unused spaces. So it's suggested that using var keyword in blocks would make your js interpreter search less for the variable, otherwise it will search the whole document in order to get the value.
In performance terms it doesn't matter, you can use as many variables as you want, the performance only will be affected by the tasks performed in the function.
As you keep increasing the variables, the heap limit set by the relevant JS engine will come into play.
For eg - V8 engine seems to have it set to 1.4 GB
If you do ever run out of that, it's high time you recheck the code & stop blaming JS.
On a serious note, from a practical point of view, that's an enormous limit, which tells you that you don't need to worry about it so much.
Besides your friendly neighborhood GC will always keep cleaning up & ensure you live lavishly with variables.
Encapsulating your code in a namespace is a good idea but you won't save memory or get a performance boost that way. From performance perspective both ways you've shown are the same.
There is a convention to avoid nameclashing however based on reverted domain - imagine a JS lib made for SO:
// The following two lines are to protect namespace from overwriting and allow to
// extend them easily
if (!com) var com = {};
if (!com.stackoverflow) com.stackoverflow = {};
com.stackoverflow.renderSomething = function(){
// Some very clever code here
};
There is nothing else you can gain this way but it's worth to organize your code this way.
And just to clarify:
function functionName(){};
is almost the same as
var functionName = function(){};
Almost because in the first form functionName is defined at parse-time and the latter form defines functionName at run-time.

Is it acceptable to call a function from a function is Node.js? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm learning Node.js by converting an existing Rails project. It's taken some time to get my head around callbacks and the async nature of Node.
The first general attempt looked ok, my RoR functionality was replicated and general speed was much faster using Node.
Having watched the nodecast here I started wondering whether my creation went against all the Node principals.
I have some function which, depending on the results call other functions. Simple, if, else if, else logic.
What I'm trying to figure out is if it's OK to do this or whether I should using something like the async package.
One particular function looks like this:
checkAuthorization: function(socket,callback) {
client.hget(socket.mac, 'authorized', function(err, val) {
callback(val);
if (val == null) {
checkExteralAuth(socket.mac, socket.serial, function(val) {
data = JSON.parse(val)
authorized = (data["live"] == 'yep') ? true : false
setRedisHash(socket.mac, 'authorized', authorized);
});
};
});
}
Is there a mode "node" way of doing this?
Why wouldn't it be? Node.js is a JavaScript platform. It's perfectly acceptable to call functions inside functions in a functional programming language. You do it all the time.
That said, sometimes you might want to avoid simply calling the function, especially with callbacks. The way you're calling the function, referenced by callback, implies that unless that function was explicitly bound to some context (using bind), you're losing the context.
Instead, callback.apply(this, [val]); might be the preferred way of going about your business.
Another thing is that since you're passing a callback function to be called later on, you might want to seriously look into using async as much as possible. I don't have an awful lot of experience with node.js, but by its very nature you'll find yourself writing callbacks, handlers and just using general async trickery all over the place.
Having a package that makes that job a lot easier is always handy...
There isn't anything fundamentally un-node-ish in this code, most libraries you will see are written exactly like this.
However, when you're working on an application, which tends to grow rather quickly, you eventually run into what is called the "callback hell", where the level of nesting reaches a level where you can have dozens of nested anonymous function calls.
This quickly becomes unmaintainable, which is where control flow libraries come in. There are several of the, the most popular ones being async and q.
async can be dropped readily into any codebase to manage callback hell, q requires architecting your code to work as Promises, but results in generally nicer API.

Categories