Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Php Object oriented, Function calling

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...