php子函數,在PHP中,在子構造函數之前調用父構造函數

1

From the sounds of it you may want to rethink your design so that you don't need to pass the parameters in the constructor. If you don't think it can be done, ask it as a question, you might be surprised by some of the suggestions.

根據它的聲音,您可能需要重新考慮您的設計,以便不需要在構造函數中傳遞參數。如果你認為這是不可能完成的,那就問它一個問題,你可能會對其中的一些建議感到驚訝。

The child class has the ability to override the parent constructor without calling it at all. I would recommend having a final method in the parent class. That way everyone knows you don't want this being overriden, and any inherited class (rightly) has access to do whatever it wants in the constructor.

子類有能力在不調用父構造函數的情況下重寫它。我建議在父類中使用final方法。這樣,每個人都知道您不希望這個類是overriden,任何繼承的類(正確地)都可以在構造函數中執行它想要的任何操作。

class Father {

private $_privateData;

final function setPrivateData($privateData) {

$this->_privateData = $privateData;

}

}

Another, not recommended, more "reinventing the wheel", solution would be to define a function in the parent class, say _construct(), that's called in its own construct. Its not really clear, doesn't use language features/constructs, and is very specific to a single application.

另一種不推薦的方法是“重新發明輪子”,解決方案是在父類(比如_construct()中定義一個函數,這個函數在它自己的構造中被調用。它不是很清楚,不使用語言特性/構造,並且只針對一個應用程序。

One last thing to keep in mind: you can't really hide information from the child class. With Reflection, serialize, var_dump, var_export and all these other convenient APIs in the php language, if there is code that shouldn't do anything with the data, then there's not really much you can do asides from not store it. There are libraries and such that help create sandboxes, but its hard to sandbox an object from itself.

最后要記住的一件事是:您不能對子類隱藏信息。有了反射、序列化、var_dump、var_export和php語言中所有其他方便的api,如果有一些代碼不應該對數據做任何處理,那么從不存儲它開始就沒有多少可做的事情了。有一些庫可以幫助創建沙箱,但是很難對對象本身進行沙箱處理。

Edit: Somehow I missed Artefacto's answer, and I suppose he is right (I've never tried writing an extension to do that). Still, implementing it breaks developer expectations while making it harder to actually see code to explain what's going in.

編輯:不知怎么搞的,我錯過了artefact的答案,我想他是對的(我從來沒有試過寫一個擴展來做這個)。盡管如此,實現它打破了開發人員的期望,同時也使實際看到代碼來解釋其中的內容變得更加困難。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值