继承的函数无法访问子类的私有变量

时间:2019-05-20 07:45:08

标签: php oop inheritance

我需要一些帮助。这段代码并不意味着要做任何我只是想学习这些继承函数如何工作的事情。

因此,父母和孩子班级都有$ wheels变量并将其设置为private(这没有意义,但我只是在玩代码)。

使用一种方法来打印实例的轮子数。子类中不会重写此方法。创建父对象和子对象,并使用每个对象调用wheel_details()。

但是,当使用子对象调用时,该方法不使用子对象的私有变量。而是打印父对象的var。

您如何以及为什么认为它访问父类的私有变量而不是其自己的私有变量。

对此有所了解。 TIA

class Bicycle {

    private $wheels = 2;


    public function wheel_details(){
        return " It has {$this->wheels} wheels. Invoked by ". get_class($this) ;
    }

}

class Unicycle extends Bicycle {

    private $wheels = 1;

}

$b1 =  new Bicycle;
$b2 =  new Unicycle;


echo "Bicycle1 wheels ". $b1->wheel_details(). " <br />";
echo "Bicycle2 wheels ". $b2->wheel_details(). " <br />";

/*Output
=======
Bicycle1 wheels It has 2 wheels. Invoked by Bicycle 
Bicycle2 wheels It has 2 wheels. Invoked by Unicycle
*/

1 个答案:

答案 0 :(得分:2)

这是设计使然:

  

声明为私有的成员只能由定义该成员的类访问。

如果要覆盖子类的值,请改用<div id="map" style="height:500px;width:100%;"></div> <script> var id=1; function initMap() { console.log("map initiated"); var directionsDisplay = new google.maps.DirectionsRenderer; var directionsService = new google.maps.DirectionsService; var map = new google.maps.Map(document.getElementById('map'), { zoom: 7, disableDefaultUI: true, center: {lat:<?php echo ($directionB[$row]['Latitude']); ?>, lng: <?php echo($directionB[$row]['Longitude']); ?>} }); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById('right-panel')); var control = document.getElementById('floating-panel'); control.style.display = 'none'; map.controls[google.maps.ControlPosition.TOP_CENTER].push(control); calculateAndDisplayRoute(directionsService, directionsDisplay); } function calculateAndDisplayRoute(directionsService, directionsDisplay) { //var start = "41.850033,-87.6500523";//document.getElementById('start').value; // var end = document.getElementById('end').value; directionsService.route({ origin: '<?php echo($direction['Latitude']); ?>,<?php echo($direction['Longitude']); ?>', destination: '<?php echo($directionB[$row]['Latitude']); ?>,<?php echo ($directionB[$row]['Longitude']); ?>', travelMode: 'DRIVING' }, function(response, status) { if (status === 'OK') { directionsDisplay.setDirections(response); } else { window.alert('Directions request failed due to ' + status); } }); } </script>