开发者

Is it possible to automatically generate PHP function names from an array of values?

I was recently taught the arrays system to shorten my code on Javascript.

        var fields = ['username', 'password', 'password_confirm', 'type', 'firstname', 'lastname', 'bdate_month', 'bdate_day', 'bdate_year', 'email', 'country', 'state', 'city', 'payment_email'];
        var length = fields.length;
        for (var i=0; i<length; i++) {
        if ($('#' + fields[i]).val() == "") {
        $('#' + fields[i] + '_error').show();
        $('#' + fields[i] + '_error').fadeOut(4000, function() {});
        $('#' + fields[i]).focus();
        return false;
        }
        }

This is the code I generated to create a series of conditionals that would validate the contents of a submit form.

Now I would like to use this same principle in PHP to generate a series of functions that will query the logged in user's data from a MySQL database.

I am a newbbie with PHP and I'm aware that the following code might be just a bunch of nonsense gibberish. But maybe you can get an idea of what I'm trying to accomplish here.

include("connect.php");

$fields = ('id', 'username', 'password', 'password_confirm', 'type', 'firstname', 'lastname', 'bdate_month', 'bdate_day', 'bdate_year', 'email', 'country', 'state', 'city', 'payment_email');
$username = mysql_real_escape_string($_SESSION['username']);

for ($i=0; $i<15; $i++) {
function $fields($i)() {
    $username = mysql_real_escape_string($_SESSION['username']);
    $sql="SELECT * FROM users WHERE username='$username'";
    $resultado=mysql_query("$sql");
    $row=mysql_fetch_array($resultado);
    if($row!=NULL)
    {
        echo ($row['$fields($i)']);
    } else {

        echo (" No ".$fields($i)." inserted!");
    }
}
}

=====================开发者_StackOverflow社区====================== EDIT:

I figured out a much easier and simpler way.

function in_user($key) { 
$username = mysql_real_escape_string($_SESSION['username']);
$sql="SELECT * FROM users WHERE username='$username'"; 
$resultado=mysql_query("$sql"); 
$row=mysql_fetch_array($resultado); 
if($row!=NULL){ 
echo ($row[$key]); 
} else { 
echo ("No {$key}!"); 
} 
}

Since all I need to be changing is the field to consult, I think an argumented function would be a lot easier and simpler.

<?php in_user('email');?> would output stored.email@database.com


In PHP you cannot create a function whose name is based on a variable.

Also, in this example you wouldn't gain much, I think it's a lot clearer to use:

function user_get_field($fieldname)

Now if you need multiple fields this would result in executing multiple queries so it's probably better to retrieve everything and cache it.

Hey, you could even store everything related to the user in the session and update it when he changes his own settings. That's only one query per session.


Well, I'm not sure about the overall approach, but just for fun.... you can use variable variables to trigger anonymous functions like this:

<?php
$fields = array('id', 'username' ...
foreach($fields as $index => $one_field) {
    $$one_field = function() use ($one_field, $index) { ... };
}

Note the use of use, so I can access the instances of $one_field and $index that were current when each $$one_field was created in the function... creating a true closure.

Now you can access one of these functions like $username()

Here's a quick illustrative example.


What are you trying to accomplish exactly? Like what is the end result supposed to do? Are you just trying to check if a field in a row is filled in? To me it just looks like you're complicating your life more than you need to.

EDIT:

Here's how I would do it. Put this in your connect.php:

$user = array();
$username = mysql_real_escape_string($_SESSION['username']);
$query = "SELECT * FROM users WHERE username='{$username}'";
$rs = mysql_query($query);
$row = mysql_fetch_array($rs);

foreach($row as $key => $value) {
    $user[$key] = $value;
}

With that, you should be able to access any of the users fields by going $user['id'] or $user['password'] provided connect.php is included.

I hope this was helpful.

EDIT 2:

Even simpler:

$username = mysql_real_escape_string($_SESSION['username']);
$query = "SELECT * FROM users WHERE username='{$username}'";
$rs = mysql_query($query);
$user = mysql_fetch_array($rs);


function fields($i) {
    $username = mysql_real_escape_string($_SESSION['username']);
    $sql="SELECT * FROM users WHERE username='$username'";
    $resultado=mysql_query($sql);
    $row=mysql_num_rows($resultado);
    if($row != 0) {
        echo ($row['$fields($i)']);
    } else {
        echo (" No ".$fields($i)." inserted!");
    }
}
for ($i=0; $i<15; $i++) {
    fields($i);
}  

That function must be out and $fields is an array, i hope it works.


I know its old, but still, this Works...

function test_one(){
print "one";
}
function test_two(){
print "two";
}
$var = "test_two";
$var();


You could just use php's fwrite, and write the function to file as you would normally. ie fwrite($handle,'<?php function '.$function_name.' { //function contents here } ?>'); I wouldn't recommend this, but it's doable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜