dougaoshang0237
dougaoshang0237
2015-06-11 15:50
浏览 41
已采纳

php中带有参数问题的构造函数

I'm not able to get the arguments passed onto a function in the constructor. Let me a bit clear with the code snippet below.

class Foo{
    public function __construct($arg){
         $arg = $arg1;
    }

    public function A($arg1){
        echo $arg1;
    }
}

$obj = new Foo();
$data = $obj->A('hello');

Here, the call is being made to the function A with an argument. I'm not able to get the same argument value in the constructor. I'm just giving an idea of my code.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongmin4990
    dongmin4990 2015-06-11 15:59
    已采纳

    Some additional examples:

    Constructor Argument

    class Foo{
        public function __construct($argument){
            echo $argument;
        }
    }
    
    new Foo('Hello World');
    

    Constructor Argument + Set argument to object as property

    class Foo
    {
        public $argument = '';     
    
        public function __construct($argument){
            $this->argument = $argument;
        }
    
        public function printIt()
        {
            echo $this->argument;
        }
    }
    
    $foo = new Foo('Hello World');
    $foo->printIt();
    
    点赞 评论
  • duanniedang3946
    duanniedang3946 2015-06-11 15:57

    In your _construct, $arg1 is not available for use, since it doesn't come from anywhere. This code would work fine if you would just remove $arg = $arg1; and remove $arg from the parameters of your constructor.

    Right now the constructor is trying to pass a value from a variable that doesn't exist on that scope to $arg.

    点赞 评论
  • douyun1860
    douyun1860 2015-06-11 15:58
    <?php
    
    class Foo {
    
        private $arg1;
    
        public function __construct($arg) {
            $this->arg1 = $arg;
        }
    
        public function A() {
            echo $this->arg1;
        }
    
    }
    
    $obj = new Foo("hello");
    $data = $obj->A();
    

    try this, it will work

    点赞 评论

相关推荐