doucuo9126 2018-01-28 16:10
浏览 245
已采纳

在某些条件下,但在整个脚本中停止其__construct中的类

I have an class. I use one Object of this Class and want to stop class in its __construct in some conditions like if user is not logged in. I have others codes after this object's line. I used die() and exit() functions, but these function stop whole of script. I just stop that class and echoes like please log in.

  • 写回答

1条回答 默认 最新

  • douxian7534 2018-01-28 16:37
    关注

    If you can assert in your constructor that your object can't be properly instantiated with the given parameter, you should throw an exception so that the rest of your program can be notified that the construction failed.

    Of course, from there, you need to catch that exception and handle it accordingly in the section of your code that is trying to construct the object.

    It could look like this:

    class MyClass
    {
        public function __construct($user) 
        {
            if(!$user->isLoggedIn()) 
            {
                throw new Exception('MyClass cannot be instantiated with a non-logged in user.');
            }
    
            /* .. rest of the constructor .. */
        }
    
        /* .. other methods .. */
    }
    

    Then in your script trying to construct an instance of MyClass, you would need to have a try/catch as follows:

    $user = getUser();
    try {
        $myObj = new MyClass($user);
    }
    catch(Exception $e) {
        // Handle this case... $myObj = null; ?
    }
    
    /* ... rest of your script ... */
    

    You might want to have a look at this page to decide what kind of exceptions you should throw and catch as you should avoid just throwing and catching an Exception instance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效