Home > Backend Development > PHP Tutorial > php数组/对象的值传递和引用传递

php数组/对象的值传递和引用传递

WBOY
Release: 2016-06-20 13:00:56
Original
1337 people have browsed it

php数组/对象的值传递和引用传递

一般的数据类型(int, float, bool)不做这方面的解说了

这里详细介绍一下数组和的类的对象作为参数进行值传递的区别

数组值传递

<?php



function main() {

        $cc = array(

            'a','b'

        );

        change($cc);

        var_dump($cc);

        die;

}

function change($cc){

        $cc = array('dd');

}

main();

?>



output:

array(2) {

  [0]=>

  string(1) "a"

  [1]=>

  string(1) "b"

}
Copy after login

数组引用传递

<?php



function main() {

        $cc = array(

            'a','b'

        );

        change($cc);

        var_dump($cc);

        die;

}

function change(&$cc){

        $cc = array('dd');

}

main();

?>

outpout:

array(1) {

  [0]=>

  string(2) "dd"

}
Copy after login

类对象值传递

<?php

class pp{

        public $ss = 0;

}

function main() {

        $p = new pp();

        change($p);

        var_dump($p);

        die;

}

function change($p){

        $p->ss = 10;

}

main();

?>

output:

object(pp)#1 (1) {

  ["ss"]=>

  int(10)

}
Copy after login

类对象引用传递

<?php

class pp{

        public $ss = 0;

}

function main() {

        $p = new pp();

        change($p);

        var_dump($p);

        die;

}

function change(&$p){

        $p->ss = 10;

}

main();

?>

object(pp)#1 (1) {

  ["ss"]=>

  int(10)

}
Copy after login

 

 总结:php中,数组是当一个普通变量,值传递是要一个实参的一个拷贝副本,跟实参无关,引用传递后可以改变实参的值
而类的对象是无论值传递和引用传递都是引用传递,是对对象的引用,都会改变实参的值


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template