PHP protected variable [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there anyway to make an variable to protected and can't overwrite to php ?
p.s: Not in class or define.
For example;
<?php
$var ="something";
$var ="test";
echo $var;
?>
I want this code return "something" not "test".
Do you have any idea about this ?

Technically you can use a helper function and the global (yuck) keyword, but classes/define is much better (but you'd still have to use a function and change all the $var = "something" lines to set_var("something")):
<?php
set_var("something");
set_var("test");
var_dump($var); //string(9) "something"
function set_var($newVar) {
static $varIsSet;
global $var;
if (!$varIsSet) {
$var = $newVar;
$varIsSet = true;
}
}
?>
DEMO

That would go against the whole point of a variable
The whole purpose of a variable is that it is variable in value, it can change later in the program.
What can I use instead?
But you could use a constant:
// Works on PHP 5.3.0 and later
const SOME_CONSTANT = "Some value.";
OR
// Far more well known, works on older PHPs, does the same thing
define("SOME_CONSTANT", "Some value");
How do I use constants?
Then use it much like you would use a variable:
echo SOME_CONSTANT;
You can use a constant in nearly any way in which you can use a variable, just traditionally you'll use an upper-case name for the constant (this isn't enforced in PHP) and it wont start with a $ symbol (this is enforced)... oh and of course, you can't re-assign it.
Note: Because constants defined using the const keyword are defined at compile time, you CANNOT use this syntax inside loop structures, if statements, switch statements etc, and must use define() instead.

You could use functions to simulate that behavior:
function var() {
return "something";
}
But if you do not want a "variable" to change, use a constant.

Related

Is it normal practice to use variables to store parameter data? [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
In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead. Is this common practice? Is this good practice?
$name = $_POST['name'];
and then they use they use $name down here to echo it or use it as a function parameter.
Another example is:
DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);
Pros:
Shorthand variables can be easier to type and remember.
A shorthand variable might allow an expensive operation to be done once instead of repeated many times. But beware of premature optimization! Most of the time this sort of optimization would be premature.
A shorthand variable can be used to make a copy that can be changed without modifying the original variable.
In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.
Cons:
Indiscriminate use of shorthand variables can result in multiple names for the same values.
In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.
I have been doing php professionally for about 5 years now.
Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:
$name = isset($_POST['name']) ? $_POST['name'] : false;
This way if the variable isn't passed then you don't get an undefined variable warning.
Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.
The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.
I would do something like this...
class ValueTooLong extends Exception {}
function R($param, $default=null, $type='string', $max_length=null) {
if(!isset($_REQUEST[$param]))
return $default;
$r = $_REQUEST[$param];
if($max_length && strlen($r) > $max_length)
throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
if($type === 'bool' || $type === 'boolean') {
if($r === 'false' || $r === 'no')
return false;
return !empty($r);
}
settype($r, $type);
return $r;
}
# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');
EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long

Is PHP function names case-sensitive or not? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am from Java background.
In Java, every method has case-sensitive while calling. But in PHP, I didn't see the case-sensitive function name while calling the functions.
class Sample {
...
...
function sampleFunction() {
....
....
}
}
$obj = new Sample();
$obj->sampleFunction(); /* Proper call with function name */
$obj->samplefunction(); /* It should show undefined function error but it also calls sampleFunction() */
Can anyone clear my doubt why this is also called even non-case sensitive function name. And please give me how to restrict in PHP?
Thanks in advance.
They are case insensitive, see this:
Note: Function names are case-insensitive, though it is usually good
form to call functions as they appear in their declaration.
http://www.php.net/manual/en/functions.user-defined.php
Functions are not case sensitive, Variables are case sensitive.
you can read more info from manual :
http://fr.php.net/manual/en/functions.user-defined.php

if statement and $_GET [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am passing a variable using GET, and I'd like a fallback if there's nothing there. I've been using
$page = $_get;
if $page = ""
{
include 'home.php';
}
else
{
include $page;
}
But it just breaks my page. Any ideas?
First, $_GET is in capitals.
Second, you need to say which value_name you want. $_GET['value_name']
Third, you need to check if the value_name has been set. if(isset($_GET['value_name']))
Fourth, and most important: NEVER DO THIS ! Never include files based on what is given in the url or otherwise user input. You will be hacked ! Rather you match the given value to an array of allowed file names or use a switch.
Probably just missing the parens on the if statement. Also, you'll need to specify the GET param.
$page = $_GET['param'];
if ($page == "") {
include 'home.php';
} else {
include $page;
}
First of all, $_GET is an associative array. So you should check against something, or not empty.
On the other hand, here $page = "" you're assigning; if you want to compare, you need to use == or ===. Also, you could use functions like isset, or empty, that will return you a bool if there is an element or not in the variable.
So, what you need is something like this
include !empty($_GET['param'])?$_GET['param']:'home.php'
? is a ternary operator, is a resumed if-else
As last aclaration, you should never include directly variables you receive from $_GET, and $_POST. This will put risk on your system. example on Stack Overflow
Also, use isset() to check if you have an input...
But yes what you want to do is a little bit dangerous in term of security... !

How to check if input is a callable construct or function? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is not a duplicate of "In PHP, how do I check if a function exists?".
http://us3.php.net/function_exists will fail if input is a language
construct (e.g. http://us1.php.net/empty).
http://us1.php.net/is_callable with $syntax_only = true will allow
language constructs (e.g. empty), though it will also allow
random_function_that_does_not_exist.
How do I check if input is callable, either as an existing function or a language construct that behaves like a function?
There are all kinds of potential problems with what you're asking. However if I understand you right, you simply want to know if somename can be called like somename('someinput').
If that's true, then it appears you need to use a combination of function_exists and a manual lookup of language constructs from the List of Keywords.
Something like this perhaps:
function canICall($function) {
$callableConstructs = array("empty","unset","eval","array","exit","isset","list");
return function_exists($function) || in_array($function, $callableConstructs);
}
That $callableConstructs array is not complete, look at the List of Keywords page to build it out.
Yes it is hackish, but without a built-in way to do this in PHP I don't see another option.
Note that just because you can call something like a function, does not make it a function, nor does it mean that it behaves like a function in other ways.
You cannot call it dynamically:
$var = "empty";
$var('someinput'); // Does NOT work
Nor does this work:
call_user_func('empty', $foo);
You could use it in an eval call, but I hope you understand the huge list of reasons why that can be dangerous.
Since empty always exists and is a language construct which cannot be called using variable functions, it doubly makes no sense to want to use function_exists on it. Even if function_exists would work, it is not possible to write this code:
$func = 'empty';
if (function_exists($func)) {
$func($var);
}
The only way to call empty() is to write it literally in your source code. You cannot call it using variable functions any more than you can do that with list() = or /.
The best you could do is:
if (function_exists('empty')) {
empty($foo);
}
But because empty always exists, what's the point in testing for it?
If you want to make a validation rule, simply write your own function:
function isEmpty($value) {
return !$value;
}
$rule = 'isEmpty';
This does exactly the same thing.
Or you make empty a special case in your rule execution:
function validate($rule, $value) {
switch ($rule) {
case 'empty' :
return !$value;
default :
if (!function_exists($rule)) {
throw new InvalidArgumentException("$rule does not exist");
}
return $rule($value);
}
}

"Indirect" isset() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
function myCheck($in)
{ return isset($in); }
$var1='Something';
$var2='$var1';
$var3='$varNonExitant';
What I'm trying to achive is to use myCheck to evaluate the existance of the content like this:
myCheck($var2) return true;
myCheck($var3) return false;
isset() is not really a function: it's a language construct. As such, it's allowed to do some magic that's not available to regular functions, such as being fed with non-existing variables.
To sum up: you cannot replicate it with a custom function.
Edit:
As DaveRandom pointed out in a comment below, all you can do is come close by checking if a variable isset for example:
function variable_isset(&$variable = NULL) {
return isset($variable);
}
This approach offers two drawbacks though:
This works by passing the unset variable by reference, thus creating it when called. As it's NULL it is still not set.
It'll trigger an Undefined variable notice if the variable does not exist, ruining the whole concept of gracefully handling optional variables.
Most likely this should not be needed. So question remains why you can not use isset in the first place which would be much more needed to give you better guidance.
When you cyall myCheck($abc), with set $abc = 123, it gets myCheck(123). It isn't any valid argument for isset.
You have to give the function a string with variable name:
function isset_global($variable_name)
{
return isset($GLOBALS[$variable_name]);
}
Of course, I am also wondering, why to do this, but it answers the question as long as you check a global variable.

Categories