Is there a possible way to combine the if function and the isset function (Or other functions) into one function.
For example:
if(isset($_GET['test'])){
echo "It exists";
}
into
exitsts($_GET['test']){
echo "It exists";
}
I searched on google and stackoverflow and used multiple ways to describe it.
But no solution.
So is there a solution for it?
Thanks in advance!
Bram Hammer
No, this is not possible. If is not a function, but a syntax element. Usually in most programming languages you have functions, which take values and return values (and maybe do something behind the back in the process) and syntax elements, which can be used to structure the code and have it behave in certain ways, for example branching (if-then-else), looping (for,while etc). The distinction in most languages is simple: If it has a block of code behind it, then it is a syntactic element, if it is somehow called, it is a function. However this may not be true for all languages.
It is usually not possible to add your own syntax elements, unless the language explicitly allows it through some meta-programming facilities, like macros or other powerful tools used to extend the language. As far as I know PHP does not offer any such tools. One way to get them for languages which do not offer them out of the box is to use an additional preprocessor, such as M4. However this is rarely useful.
Some languages also allow treating blocks of code as values, so in that case you can use functions in a similar way as syntactic elements, passing them code which has not yet been evaluated. If blocks of code cannot be directly used, maybe the language offers anonymous functions or anonymous classes, which can be used to simulate this. However usually these simulated control-structures are not nearly as nice looking as the built in control structures. I am not sure whether PHP allows anonymous functions, or classes, you may be able to build something like the structure you want, but it will look very ugly.
create custom function:
function exitsts($var){
if(isset($var)){
return "It exists";
}
else{
return "doesn't exsits";
}
}
then do your check:
echo exitsts($_GET['test']);
There is, use empty
if(!empty($_GET['test'])){
/* matches
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
*/
}
Related
This is what w3School says about the strpos() function :
Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.
How is the function defined? Is it possible to write such functions which returns values of 2 different datatypes in other languages as well?
Many dynamically typed languages allow you to return whatever you want from a function. Strongly typed languages generally don't.
In PHP a function can return anything it wants, including booleans, ints, strings, null, arrays, all kinds of objects, whatever you need. It's the same in for example Javascript and Lua, which are also dynamically typed.
Just make sure to check the return type of the function if it can be different kinds of things. Especially with things like int(0) and false, which are considered equivalent if you use an == comparison. Use === to make sure it's the right type.
Other languages do not have loosely typed variables and function returns. Take for example C.
Taken from php.net:
PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.
I'm creating a global file to hold items that will be re-used throughout my website. What are the differences between these two lines of code? Is one "better" than the other?
This:
$logo = "img/mainlogo.jpg";
vs this:
function logo() {
echo "img/mainlogo.jpg";
}
You should code clear and readable and split in the html and php. The performance profit is not significant...
<?php
...
$logo = "img/mainlogo.jpg";
...
?>
...
<img src="<?= $logo ?>" alt="logo">
...
Of the two options you posted, the function is the better choice. But, to be brutally honest, this sort of thing is exactly what constants are for:
defined('MAIN_LOGO') || define('MAIN_LOGO','img/mainlogo.jpg');
suppose you're working on a site that has to support multiple languages, then you can simply use the same trick:
defined('CLIENT_LOCALE') || define('CLIENT_LOCATE',$whereverYouGetThisFrom);
defined('MAIN_LOGO') || define('MAIN_LOGO','img/mainlogo_'.CLIENT_LOCALE.'.jpg');
//if language is EN, mainlogo_EN.jpg will be used, if lang is ES, mainlogo_ES.jpg, etc...
Besides, a constant, once defined cannot be redefined (clue is in the name, of course). Also: since PHP still has a lot of C-stuff going under the bonnet, and you've tagged this question performance, it might interest you that constants are much like C's macro's, which are a lot faster than regular function calls, or even C++ inline functions (even if they were indeed compiled as inline functions).
Anyway, if you have a ton of these things you want to centralize, either think of creating a couple of ini files for your project, and parse them into some sort of global object
Functions are good.
I see that function logo() is better than $logo. echo doesn't take much memory, but $logo does. Even though, function logo() takes something, it will be handled by PHP's very own garbage collector. You can also use these functions to ensure that you are not misusing the memory allocated.
memory_get_peak_usage();
memory_get_usage();
Explanation:
Upon the ending of an in use function PHP clears the memory it was using, at least more efficiently than if not using a function. If you are using recursive code or something similar that is memory intensive try putting the code into a function or method, upon closing of the function/method the memory used for the function will be garbaged much more efficiently than that of unsetting variables within the loop itself.
Source: 7 tips to prevent PHP running out of memory
The main purpose of a function is to avoid code repetition and perform a specific task. Based on that definition, using a function to only return a value is a bad design.
In that context I think is better a good readability in the code than to save several bytes of memory. We are in 2012, optimization is good but this type of micro-optimization is simply ridiculous. I prefer assigning a variable, it's clear and do what you expect.
$logo = "img/mainlogo.jpg"; can be redefined naturally later without changing code by doing this $logo="img/newmainlogo.jpg"; whereas the function would have to be modified itself, in its first definition.
I'm wondering what you think the best practice is here-- does it buy you very much to type-check parameters in PHP? I.e have you actually seen noticeably fewer bugs on projects where you've implemented parameter type-checking vs. those that don't? I'm thinking about stuff like this:
public function __construct($screenName, $createdAt) {
if (!is_string($screenName) || !is_string($createdAt) {
return FALSE;
}
}
Normally within a PHP application that makes use of the skalar variable "types" is bound to actually string input (HTTP request). PHP made this easier so to convert string input to numbers so you can use it for calculation and such.
However checking scalar values for is_string as proposed in your example does not make much sense. Because nearly any type of variable in the scalar family is a string or at least can be used as a string. So as for your class example, the question would be, does it actually make sense to check the variable type or not?
For the code you proposed it does not make any sense because you exit the constructor with a return false;. This will end the constructor to run and return a not-properly-initialized object.
Instead you should throw an exception, e.g. an InvalidArgumentException if a constructors argument does not provide the expected / needed type of value.
Leaving this aside and taking for granted that your object constructor needs to differ between a string and an integer or bool or any other of the scalar types, then you should do the checks.
If you don't rely on the exact scalar types, you can cast to string instead.
Just ensure that the data hidden inside the object is always perfectly all-right and it's not possible that wrong data can slip into private members.
It depends. I'll generally use the type-hinting that is built into PHP for higher-level objects ((stdClass $obj, array $arr, MyClass $mine)), but when it comes to lower level values -- especially numbers and strings, it becomes a little less beneficial.
For example, if you had the string '12345', that becomes a little difficult to differentiate between that and the number 12345.
For everything else, the accidental casting of array to a string will be obvious. Class instances which are cast to strings, if they don't have a __toString, will make PHP yell. So your only real issue is classes which have a __toString method and, well, that really limits the number of times where it can come up. I really wonder if it is worth that level of overhead.
Checking function arguments is a very good practice. I suspect people often don't do that because their functions grow bigger and the code becomes uglier and less readable. Now with PHP 7 you can type-hint scalar types but there is still no solution for cases when you want your parameter to be one of two types: array or instance of \Traversable (which both can be traversed with foreach).
In this case, I recommend having a look at the args module from NSPL. The __constructor from your example will have the following look:
public function __construct($screenName, $createdAt)
{
expectsAll(string, [$screenName, $createdAt]);
}
// or require a non-empty array, string or instance of \ArrayAccess
function first($sequence)
{
expects([nonEmpty, arrayAccess, string], $sequence);
return $sequence[0];
}
More examples here.
Better documentation is more important when you're the only one interacting with the methods. Standard method definition commenting gives you well documented methods that can easily be compiled into an API that is then used in many IDEs.
When you're exposing your libraries or your inputs to other people, though, it is nice to do type checking and throw errors if your code won't work with their input. Type checking on user input protects you from errors and hacking attempts, and as a library letting other developers know that the input they provided is not what you're expecting is sometimes nice.
I keep coming across statements like:
echo is a language construct but
print is a function and hence has a
return value
and
die is a language construct
My question is what are these language constructs and more importantly why do we need them?
Language constructs are hard coded into the PHP language. They do not play by normal rules.
For example, whenever you try to access a variable that doesn't exist, you'd get an error. To test whether a variable exists before you access it, you need to consult isset or empty:
if (isset($foo))
If isset was a normal function, you'd get a warning there as well, since you're accessing $foo to pass it into the function isset. Since isset is a language construct though, this works without throwing a warning. That's why the documentation makes a clear distinction between normal functions and language constructs.
Language constructs are what makes up the language: things like "if" "for" "while" "function" and so on.
The mentions in the PHP manual of things like "echo", "die" or "return" are there to make it clear that these are NOT functions and that they do not always behave like functions.
You could call "echo" as "echo()" so it may confuse beginners. That's why they put the clear disinction in the manual. To make it absolutely clear to everyone.
Other examples for language constructs that could be mistaken for functions are "array()", "list()" and "each()".
To understand the answer for this question you must understand how parsers work. A language is defined by syntax and the syntax is defined through keywords.
The language constructs are pieces of code that make the base of PHP language. The parser deals with them directly instead of functions.
Not all of a language can be functions. There must be some base, somewhere, on which you implement those first functions. The elements of this base are the language constructs (alternately, built-ins). They don't always behave like "normal" functions do.
For the sake of completeness, a language construct is any instruction which is built into the language itself, while a function is an additional block of code.
In some cases, a language may choose to build in a particular feature or to rely on a separate function.
For example, PHP has the print language construct, which outputs a string. Many other languages, such as C don’t build it in, but implement it as a function. There might be technical reasons for taking one or other approach, but sometimes it is more philosophical — whether the feature should be regarded as core or additional.
For practical purposes, while functions follow a rigid set of logistic rules, language constructs don’t. Sometimes, that’s because they may be doing something which would otherwise traumatise a regular function. For example, isset(…), by its very purpose, may be referencing something which doesn’t exist. Functions don’t handle that at all well.
Here are some of the characteristics of language constructs:
Many don’t require parentheses; some do sometimes.
Language Constructs are processed in a different stage; functions are processed later
Some Language Constructs, such as isset do things which would be impossible as functions; some others, such as Array(…) could have gone either way.
Some Language Constructs certainly don’t look like functions. For example, the Array(…) construct can be written as […].
As the documentation keeps reminding us, language constructs cannot be referenced as variable variables. So $a='print_r'; $a(…); is OK, but $a='print'; $a(…); isn’t.
Some things are just not possible using normal functions, consider this snippet:
list($el1, $el2) = array('el1', 'el2');
What it does is it takes the elements from a non-associative array and assigns the values to the variables defined in the list() construct.
Simply cannot be done with functions :)
A more subtle example is issetand empty. Though they look like functions, they one thing that's not possible with functions alone – they do not generate "variable is undefined" or "undefined index" notices.
language constructs can be formed in more than one way and has a return-value
print("asdf"); is as possible as print "asdf"; and will return 1.
echo("asdf"); is equal to echo "asdf;" but has no return-value.
die("asdf"); is equal to exit("asdf"); and hasn't a return-value too.
I am not really clear about declaring functions in php, so I will give this a try.
getselection();
function getselection($selection,$price)
{
global $getprice;
switch($selection)
{
case1: case 1:
echo "You chose lemondew <br />";
$price=$getprice['lemondew'].'<br>';
echo "The price:".$price;
break;
Please let me know if I am doing this wrong, I want to do this the correct way; in addition, php.net has examples but they are kind of complex for a newb, I guess when I become proficient I will start using their documentation, thank you for not flaming.
Please provide links that might also help me clear this up?
Your example seems valid enough to me.
foo('bar');
function foo($myVar)
{
echo $myVar
}
// Output: bar
See this link for more info on user-defined functions.
You got off to a reasonable start. Now all you need to do is remove the redundant case 1:, close your switch statement with a } and then close your function with another }. I assume the global array $getprice is defined in your code but not shown in the question.
it's good practice to declare functions before calling them. It'll prevent infrequent misbehavior from your code.
The sample is basically a valid function definition (meaning it runs, except for what Asaph mentions about closing braces), but doesn't follow best practices.
Naming conventions: When a name consists of two or more words, use camelCase or underscores_to_delineate_words. Which one you use isn't important, so long as you're consistent. See also Alex's question about PHP naming conventions.
Picking a good name: a "get" prefix denotes a "getter" or "accessor"; any method or function of the form "getThing" should return a thing and have no affects visible outside the function or object. The sample function might be better called "printSelection" or "printItem", since it prints the name and price of the item that was selected.
Globals: Generally speaking, globals cause problems. One alternative is to use classes or objects: make the variable a static member of a class or an instance member of an object. Another alternative is to pass the data as an additional parameter to the function, though a function with too many parameters isn't very readable.
Switches are very useful, but not always the best choice. In the sample, $selection could easily hold the name of an item rather than a number. This points to one alternative to using switches: use an index into an array (which, incidentally, is how it's done in Python). If the cases have the same code but vary in values used, arrays are the way to go. If you're using objects, then polymorphism is the way to go--but that's a topic unto itself.
The $price parameter appears to serve no purpose. If you want your function to return the price, use a return statement.
When you called the function, you neglected to pass any arguments. This will result in warnings and notices, but will run.