LoginSignup
2
2

More than 5 years have passed since last update.

[ノート]『PHP Cookbook 』を読む(CH06 関数)

Last updated at Posted at 2017-11-12

//6.1 Accessing Function Parameters

function commercial_sponsorship($letter, $number) {
    print "This episode of Sesame Street is brought to you by ";
    print "the letter $letter and number $number.\n";
}
commercial_sponsorship('G', 3);
$another_letter = 'X';
$another_number = 15;
commercial_sponsorship($another_letter, $another_number);

// any changes you make to your copy don’t alter the original value.

function add_one($number) {
    $number++;
}
$number = 1;
add_one($number);
print $number;
print "<br>";
// 6.2 Setting Default Values for Function Parameter
// the assigned value must be a constant, such as a string or a number. It can’t be a variable
function wrap_in_html_tag($text,$tag='strong'){
    return "<$tag>$text</$tag>";
}

print wrap_in_html_tag("Hello!");
print wrap_in_html_tag("Look over there","em");
print "<br>";

//6.3 Passing Values by Reference

function wrap_in_html_tag01(&$text, $tag = 'strong') {
    $text = "<$tag>$text</$tag>";
}


$text="Hey man";
print $text;
print"<br>";
wrap_in_html_tag01($text);
print $text;
//6.5 Enforcing Types of Function Arguments

function must_be_an_array(array $fruits) {
    foreach ($fruits as $fruit) {
    print "$fruit\n"; }
}
function array_or_null_is_ok(array $fruits = null) {
    if (is_array($fruits)) {
    foreach ($fruits as $fruit) {
        print "$fruit\n";
    }
    }
}
print "<br>";
//6.6Creating Functions That Take a Variable Number of Arguments

//Pass the function a single array-typed argument and put your variable arguments inside the array:
function mean($numbers){
    $sum=0;

    $size=count($numbers);

    for($i=0;$i<$size;$i++){
        $sum+=$numbers[$i];
    }

    $average=$sum/$size;

    return $average;
}

$mean=mean(array(96,93,98,98));
print $mean;
print "<br>";

// Accessing function parameters without using the argument list

    // find the "average" of a group of numbers
    function mean01() {
       // initialize to avoid warnings $sum = 0;
        $sum=0;
        // the arguments passed to the function
        $size = func_num_args();
        // iterate through the arguments and add up the numbers

        for($i=0;$i<$size;$i++){
            $sum += func_get_arg($i);
        }
        // divide by the amount of numbers
        $average = $sum / $size;
        // return average
        return $average;
    }
    // $mean is 96.25
    $mean = mean01(96, 93, 98, 98);
    print "$mean";

print "<br>";
//6.7 Returning Values by Reference
function &array_find_value($needle,&$haystack){
    foreach ($haystack as $key => $value){
        if($needle==$value){
            //When returning a reference from a function, you must return a reference to a variable, not a string
            return $haystack[$key];
        }
    }
}

$minnesota = array('Bob Dylan', 'F. Scott Fitzgerald', 'Prince', 'Charles Schultz');
$prince= &array_find_value('Prince',$minnesota);
$prince = 'O(+>';
print_r($minnesota);
print "<br>";
//6.8 Returning More Than One Value
function array_starts($values){
    $min=min($values);
    $max=max($values);
    $mean=array_sum($values)/count($values);

    return array($min,$max,$mean);
}

$values=array(1,3,5,9,13,1442);
list($min,$max,$mean)=array_starts($values);
print $min;
print "<br>";
print $max;
print "<br>";
print $mean;
print "<br>";
//6.9 Skipping Selected Return Values
//Only care about minutes
function time_parts($time){
    return explode(':',$time);
}
list(,$minute,)=time_parts('12:34:56');
print $minute;
print "<br>";
//6.10 Returning Failure
function lookup($name){
    if(empty($name)){
        return false;
    }
}
//6.11 Calling Variable Functions
function get_file($filename){
    return file_get_contents($filename);
}

$function='get_file';
$filename='graphic.png';

call_user_func($function,$filename);

//Use call_user_func_array() when your functions accept differing argument counts;
function get_file01($filename){
    return file_get_contents($filename);
}
function put_file($filename,$d){
    return file_put_contents($filename,$d);
}


if($action=='get'){
    $function='get_file';
    $args=array('graphic.png');
}elseif ($action=='put'){
    $function='put_file';
    $args=array('graphic.png',$graphic);
}

call_user_func($function,$args);

//extends
// logging function that accepts printf-style formatting
// it prints a time stamp, the string, and a new line

function logf(){
    $date=date(DATE_RSS);
    $args=func_get_args();
    var_dump($args);

    return print "$date:".call_user_func_array("sprintf",$args)."\n";
}

logf('<a href="%s">%s</a>','http://developer.ebay.com','eBay Developer Program');

//If you have more than two possibilities to call, use an associative array of function names:
$dispatch=array(
    'add' => 'do_add',
    'commit' =>'do_commit',
    'checkout' => 'do_checkout',
    'update' =>'do_update'
);

$cmd=(isset($_REQUEST['command'])?$_REQUEST['command']:'');

if(array_key_exists($cmd,$dispatch)){
    $function=$dispatch[$cmd];
    call_user_func($function);

}else{
    error_log('Unknown coommand $cmd');
}

//6.12 Accessing a Global Variable Inside a Function
// access a global variable inside a function.

$chew_count=3;
$fruit=array('banana','apple','orange');

function eat_fruit($fruit){
    global $chew_count;

    for($i=$chew_count-1;$i>0;$i--){
        print "eat $fruit[$i]";
    }
}

eat_fruit($fruit);
print "<br/>";
//6.13 Creating Dynamic Functions
$increment=7;
$add=function($i,$j)use($increment){
    return $i+$j +$increment;};
$sum=$add(1,2);
print $sum;

//A frequent use for anonymous functions is to create custom sorting functions for usort() or array_walk():

$files=array('ziggy.txt', '10steps.doc', '11pants.org', "frank.mov");
usort($files,function ($a,$b){
    return strnatcasecmp($b,$a);
});
print_r($files);
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2