在php中创建函数[重复]

This question already has an answer here:

I have the class people

ex:

class People{
   function name($name){
      echo "the name".$name;
   }
}

how to make a class calling function automatically without having to call the method :

$var=new People ()

please give me the answer?

</div>

You are looking for the Constructor.

class Bla {
 public function __construct() { // runs when class is instantiated
 }
}

Every time you create instance constructor is called you just need to explicitly add it in your class.E.g:

class People{

    public function __construct() {
        echo 'constructing';
    }

   function name($name){
      echo "the name".$name;
   }
}

But before start doing actual stuff, I recommend reading: http://php.net/manual/en/language.oop5.php

Edit: From your comments it seems you want to call method statically. If you want to call a method without instantiating you should mark function as static. In your example:

public static function name($name){
  echo "the name".$name;
}

And usage:

Person::name('my name');

Add a constructor function:

function __construct() {
   $this->name("My name");
}

This does not make a whole lot of sense though, but it's what you asked for :-)

you can do what you want by using a constructor. In php this is done by declaring a method in the class called __construct(). The constructor is run any time the object is created. so in your example

<?php
class People{
     public function __construct($name)
     {
         name($name);
     }
     function name($name){
        echo "the name".$name;
     }
}
$var = new People("dave");

the other thing you may be referring to is statics but you do call a method you just dont instantiate an instance of the class

  <?php

class People{
     static function name($name){
        echo "the name".$name;
     }
}
People::name("Dave"); 

this will output "the nameDave"

Test this:

class Family {

    private $myself;
    private $mother = '';
    private $father = '';

    public function __construct($myname) {
        $this->myself = $myname;
    }

    public function printFamily() {
        print_r($this);
    }

    public function setFather($name) {
        $this->father = $name;
    }

    public function setMother($name) {
        $this->mother = $name;
    }

}


$fam = new Family('George Walker Bush');

$fam->setFather('George Herbert Walker Bush');
$fam->setMother('Barbara Pierce Bush');

$fam->printFamily();