php 5 新增参数限定符

Taking the Hint: Object Types
Just as an argument variable can contain any primitive type, by default it can contain an object of any
type. This flexibility has its uses but can present problems in the context of a method definition.
Imagine a method designed to work with a ShopProduct object:
class ShopProductWriter {
    public function write( $shopProduct ) {
        $str  = "{$shopProduct->title}: " .
                $shopProduct->getProducer() .
                " ({$shopProduct->price})\n";
        print $str;
    }
}
You can test this class like this:
$product1 = new ShopProduct( "My Antonia", "Willa", "Cather", 5.99 );
$writer = new ShopProductWriter();
$writer->write( $product1 );
This outputs

My Antonia: Willa Cather (5.99)
The ShopProductWriter class contains a single method, write(). The write() method accepts a
ShopProduct object and uses its properties and methods to construct and print a summary string. I used
the name of the argument variable, $shopProduct, as a signal that the method expects a ShopProduct
object, but I did not enforce this. That means I could be passed an unexpected object or primitive type
and be none the wiser until I begin trying to work with the $shopProduct argument. By that time, my
code may already have acted on the assumption that it has been passed a genuine ShopProduct object.
You might wonder why I didn't add the write() method directly to ShopProduct. The reason lies with areas of
responsibility. The ShopProduct class is responsible for managing product data; the ShopProductWriter is
responsible for writing it. You will begin to see why this division of labor can be useful as you read this chapter.
To address this problem, PHP 5 introduced class type hints. To add a type hint to a method
argument, you simply place a class name in front of the method argument you need to constrain. So I
can amend the write() method thus:
    public function write( ShopProduct $shopProduct ) {
        // ...
    }
Now the write() method will only accept the $shopProduct argument if it contains an object of type
ShopProduct. Let’s try to call write() with a dodgy object:
class Wrong { }
$writer = new ShopProductWriter();
$writer->write( new Wrong() );
Because the write() method contains a class type hint, passing it a Wrong object causes a fatal error.
PHP Catchable fatal error:  Argument 1 passed to ShopProductWriter::write() must be an
instance of ShopProduct, instance of Wrong given ...
This saves me from having to test the type of the argument before I work with it. It also makes the
method signature much clearer for the client coder. She can see the requirements of the write() method
at a glance. She does not have to worry about some obscure bug arising from a type error, because the
hint is rigidly enforced.
Even though this automated type checking is a great way of preventing bugs, it is important to
understand that hints are checked at runtime. This means that a class hint will only report an error at the
moment that an unwanted object is passed to the method. If a call to write() is buried in a conditional
clause that only runs on Christmas morning, you may find yourself working the holiday if you haven’t
checked your code carefully.
Type hinting cannot be used to enforce primitives like strings and integers in your arguments. For
these, you must fall back on type checking functions such as is_int() in the body of your methods. You
can, however, enforce array arguments:

function setArray( array $storearray ) {
        $this->array = $storearray;
    }
Support for array hinting was added to the language with version 5.1. Support for null default values
in hinted arguments was another late addition. This means that you can demand either a particular type
or a null value in an argument. Here’s how:
    function setWriter( ObjectWriter $objwriter=null ) {
        $this->writer = $objwriter;
    }
So far, I have discussed types and classes as if they were synonymous. There is a key difference,
however. When you define a class you also define a type, but a type can describe an entire family of
classes. The mechanism by which different classes can be grouped together under a type is called
inheritance. I discuss inheritance in the next section.

转载于:https://www.cnblogs.com/joe-yang/archive/2010/11/08/1872164.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值