在子类问题中设置父类变量

时间:2018-11-07 10:56:27

标签: php

为什么调用getLivePath();getDevPath();方法时文件名不包含在路径中?

<?php

class supplierImport {
    var $_supplierFilename = '';
    var $_fileName = '';
    var $_livePath = '/var/www/vhosts/myshop.co.uk/httpdocs/_import/';
    var $_devPath = '/var/www/web-ecommerce/www/_import/';


    function supplierImport($supplier){
        switch($supplier){
            case 'birlea';
            $birlea = new birlea();
            break;
            case 'julianbowen';
            $julianbowen = new julianbowen();
            default;
            echo 'Supplier not available';
            break;
        }

    }

    function getLivePath(){
        return $this->_livePath.'/'.$this->_fileName;
    }

    function getDevPath(){
        return $this->_devPath.'/'.$this->_fileName;
    }

}


class birlea extends supplierImport {
    function birlea(){
        $this->_fileName = 'birlea_stock.csv';
    }
}

class julianbowen extends supplierImport {
    function julianbowen(){
        $this->_fileName = 'julianbowen_stock.csv';
    }
}

$supplierImport = new supplierImport('birlea');
echo $supplierImport->getLivePath();
echo $supplierImport->getDevPath();

这是我得到的输出:

 /var/www/vhosts/myshop.co.uk/httpdocs/_import///var/www/web-ecommerce/www/_import//

示例代码:

http://sandbox.onlinephpfunctions.com/code/435a4b25db44d2c8bb33ff6aa2d96c6db21ef177

1 个答案:

答案 0 :(得分:1)

您正在扩展基类,因此您必须实例化扩展基类的类。然后扩展类将运行其构造函数以正确设置值。

<?php

class supplierImport {
    var $_supplierFilename = '';
    var $_fileName = '';
    var $_livePath = '/var/www/vhosts/myshop.co.uk/httpdocs/_import/';
    var $_devPath = '/var/www/web-ecommerce/www/_import/';

    function getLivePath(){
        return $this->_livePath.$this->_fileName;
        // removed unnecesary `.'/'.`
    }

    function getDevPath(){
        return $this->_devPath.$this->_fileName;
        // removed unnecesary `.'/'.`
    }
}


class birlea extends supplierImport {
    function birlea(){
        $this->_fileName = 'birlea_stock.csv';
    }
}

class julianbowen extends supplierImport {
    function julianbowen(){
        $this->_fileName = 'julianbowen_stock.csv';
    }
}

$birlea = new birlea();
echo 'Birlea Live = ' . $birlea->getLivePath();
echo PHP_EOL;
echo 'Birlea Dev = ' . $birlea->getDevPath();
echo PHP_EOL;
$julian = new julianbowen();
echo 'Julian LIVE = ' . $julian->getLivePath();
echo PHP_EOL;
echo 'Julian DEV = ' . $julian->getDevPath();

结果

Birlea Live = /var/www/vhosts/myshop.co.uk/httpdocs/_import/birlea_stock.csv
Birlea Dev = /var/www/web-ecommerce/www/_import/birlea_stock.csv
Julian LIVE = /var/www/vhosts/myshop.co.uk/httpdocs/_import/julianbowen_stock.csv
Julian DEV = /var/www/web-ecommerce/www/_import/julianbowen_stock.csv