将参数传递给Codeigniter中的__construct库

时间:2017-10-16 17:30:23

标签: php codeigniter construct

我对Codeigniter很陌生,只是从头学习。检查from selenium import webdriver from bs4 import BeautifulSoup url = 'https://www.hockey-reference.com/boxscores/201610130TBL.html' driver = webdriver.Firefox() driver.get(url) data = driver.page_source driver.quit() soup = BeautifulSoup(data,'lxml') get_table = soup.find_all(class_="overthrow table_container") print(len(get_table)) 上的文档,但我的示例没有成功:

我需要将值传递给Creating Libraries库。

class:libraries / Myclasses / Bird

__construct

class:libraries / Mybird

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Bird{
 public $fly;
 public $goodsound;

 public function __construct($fly, $goodsound) {
    $fly = $this->fly;
    $goodsound = $this->goodsound;
 }
 public function sentance(){
    return "This Bird can ".$this->fly . " and has ". $this->goodsound;
 }
}

控制器:鸟类

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed'); 
require_once(APPPATH.'libraries/Myclasses/Bird.php');

class Mybird extends Bird {
  public function __construct() {
  }
}

我认为Mybird类中的问题是没有传递值,但我无法弄清楚如何处理它。

2 个答案:

答案 0 :(得分:1)

问题出现在Bird的构造函数中。试试这个。

class Bird{
    public $fly;
    public $goodsound;

    public function __construct($fly, $goodsound)
    {
        $this->fly = $fly;
        $this->goodsound = $goodsound;
    }

在属性名称之前没有$this->,您将创建在构造函数结束时超出范围的局部变量。

其次,任何扩展Bird的类都应该将两个参数传递给基类构造函数。例如:

class Mybird extends Bird {
  public function __construct() 
  {
      parent::__construct('Fly', 'very good');
  }
}

您可以定义Mybird以接受参数,然后将这些参数传递给parent :: __ construct

class Mybird extends Bird {
  public function __construct($fly, $goodsound) 
  {
      parent::__construct($fly, $goodsound);
  }
}

控制器中不需要new调用 - $this->load->library('Mybird', $config);已经为您做了。

index()应该可以正常工作,如下所示。请注意,Mybird是控制器的属性,因此需要使用$this进行访问。

 public function index(){
    echo $this->Mybird->sentance();
 }

但是,如果要在加载库时传递$config数组作为参数,则需要同时修改BirdMybird类。

class Bird
{
    public $fly;
    public $goodsound;

    public function __construct($config)
    {
        $this->fly = $config['fly'];
        $this->goodsound = $config['goodsound'];
    }

}


class Mybird extends Bird
{
    public function __construct($config)
    {
        parent::__construct($config);
    }

}

答案 1 :(得分:0)

当使用Mybird

从控制器Bird调用库时,还需要将库$this->load->library('Mybird', $config);设置为其构造函数中的参数除外

扩展库时,你需要坚持你的config.php中设置的东西,像$config['subclass_prefix'] = 'MY_';这样的东西需要MY_Bird而不是Mybird

有关主题herehere

的更多信息