dsg41888 2016-07-12 18:02
浏览 47

php - 从扩展类调用静态函数

I cant manage to call a static function (with a constant) from a extended class. Here is my code:

(1st file)
class A
{                        
    function isXSet()
    {
        return X;
    }        
    public static function setX()
    {
        define('X', 1);
    }
}  

(second file)

include('/*first file*/');
class B extends A
{        
    A::setX();        
}

How can i manage to do that ?

  • 写回答

1条回答 默认 最新

  • dsbowmvth16379079 2016-07-12 18:21
    关注

    Your code here

    class B extends A
    {        
        A::setX();        
    }
    

    is a little off. You didn't put your call inside of a method.

    class B extends A
    {   
        public static function doSomething() {     
            A::setX();
        }
    }
    

    This isn't actually doing anything by means of the parent/child relationship. In fact, after you define class A, the call to A::setX() can happen anywhere since it's public and static. This code is just as valid:

    class A
    {
        function isXSet()
        {
            return X;
        }
        public static function setX()
        {
            define('X', 1);
        }
    }
    
    class B { // No extending!
        function isXSet() {
            return A::isXSet();
        }
    }
    

    What you're more likely looking for is parent instead:

    class A
    {
        public function isXSet()
        {
            return X;
        }
    
        protected static function setX()
        {
            define('X', 1);
        }
    }
    
    class B extends A
    {   
        public static function doSomething() {     
            parent::setX();
            var_dump( parent::isXSet() ); // int(1)
        }
    }
    

    A big plus here is that extending classes can access protected methods and properties from the parent class. This means you could keep everyone else from being able to call A::setX() unless the callee was an instance of or child of A.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?