学习php 类,遇到一个基础问题,求好心人解答。

WBOY
Release: 2016-06-23 13:54:51
Original
793 people have browsed it

代码如下图,蓝色执行显示1,红色显示6 ,需要的是显示6;

请问bbb()中怎么才能使用aaa()中的$c呢?只有通过红色框中那方法吗?(感觉好麻烦)
如果不用红色框中那样的方法,但aaa()中有很多个$c这样的变量,这些变量在bbb()中需要用到,该怎么办?


回复讨论(解决方案)

你这个是函数的传参问题

如果  function bbb(){}  声明的时候没有指定传入的参数的话,那就算你调用的时候,传入再多的也是无用的,总是返回$c 也就是1的。 你必须得指定函数参数才能行。

你的 bbb 方法中的这句
    $c = $c + 1;
会有一个 Notice:  Undefined variable: c 警告 ($c 没有定义就取值了)
虽然你屏蔽了 E_NOTICE 级别的错误信息,但并不表示不存在问题。尽管在这里无碍大局

class ceshi {  public function aaa($a) {    $this->c = $a;    $r = $this->bbb();    echo $r;  }  public function bbb() {    $c = $this->c + 1;    return $c;  }}$xyz = new ceshi;$xyz->aaa(5);
Copy after login

这样就输出 6 了

//使用类的属性class ceshi {private $c;  public function aaa($a) {    $this->c = $a;    echo $this->bbb();  }  public function bbb() {    return $this->c + 1;  }}$xyz = new ceshi;$xyz->aaa(5);
Copy after login

使用??性?量就可以了。

private $c; 再?中任何function都可以?用到。

class ceshi{	private $c;	public function aaa($a){		$this->c = $a;		$k = $this->bbb();		echo $k;	}	public function bbb(){		$this->c = $this->c + 1;		return $this->c;	}}$xyz = new ceshi;$xyz->aaa(5);
Copy after login

变量的作用域问题,4楼的方法就可以用了哈

感谢楼上各位!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!