Php面向对象,函数调用 [英] Php Object oriented, Function calling

查看:146
本文介绍了Php面向对象,函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的php页面 persona.php

 <?php 
级角色{
private $ name;
public function __construct($ n){
$ this-> name = $ n;
}
public function getName(){
return $ this-> name;


public function changeName($ utente1,$ utente2){
$ temp = $ utente1-> name;
$ utente1-> name = $ utente2-> name;
$ utente2-> name = $ temp;

}
}
?>

persona 很简单,只显示构造函数和一个函数,如果调用了两个用户名称。

b $ b

 <?php 
require_oncepersona.php;
$ utente1 =新角色(Marcello);
打印第一个用户:< b>。 $ utente1->的getName()。 < / B><峰; br><峰; br> 中;
$ utente2 =新角色(Sofia);
打印第二位用户:< b>。 $ utente2->的getName()。 < / B><峰; br> 中;
changename($ utente1,$ utente2);
print名称更改后测试:第一个用户。 $ utente1-> getName()。< / b>第二位用户。 $ utente2->的getName();
?>

我不明白如何调用 changeName 函数来自这里。

解决方案

我可以理解混淆的起因在哪里...我想你不确定你是否应在 $ utente1 $ utente2 上调用 changename 。从技术上讲,你可以从任何一个对象中调用它,因为它们都是 Persona



的实例。但是为了清晰(和理智) ,我会建议在其声明中将 changeName 函数转换为静态函数



public static function changeName($ utente1,$ utente2){



然后在你的index.php你可以这样称呼它:



Persona :: changename($ utente1,$ utente2);

从体系结构标记点来看,这有助于更好地理解该函数与Persona类绑定,并且对象可以使用该类函数更改交换名称,而不是使它成为实例函数,然后让任何对象执行它。


This is my php page persona.php:

<?php
 class persona {
 private $name;
 public function __construct($n){
    $this->name=$n;
 }
 public function getName(){
    return $this->name;
}

public function changeName($utente1,$utente2){
    $temp=$utente1->name;
    $utente1->name=$utente2->name;
    $utente2->name=$temp;

    }
}
?>

The class persona is simple and just shows the constructor and a function that change two users name if called.

This is index.php:

<?php
require_once "persona.php" ;
    $utente1 = new persona("Marcello");
    print "First user: <b>". $utente1->getName()."</b><br><br>";
    $utente2 = new persona("Sofia");
    print "Second user: <b>". $utente2->getName()."</b><br>";
    changename($utente1,$utente2);
    print " Test after name changes: first user". $utente1->getName()."</b> second user". $utente2->getName();
?>

What I do not understand is how to call the changeName function from here.

解决方案

I can understand where the confusion arises from...I think you are unsure if you should call changename on $utente1 or $utente2. Technically you can call it from either objects because they are both instances of Persona

But for clarity (and sanity), I would recommend converting the changeName function to a static function in its declaration:

public static function changeName($utente1,$utente2){

and then in your index.php you can call it as:

Persona::changename($utente1,$utente2);

From an architecture stamp point, this will help provide a better sense that the function is tied to the class of Persona, and objects can change swap names using that class function, as opposed to making it an instance function and then having any object execute it.

这篇关于Php面向对象,函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆