arashdalir / php-classfriendship
此包最新版本(v1.2.0)没有可用的许可信息。
此库提供了模拟C++中类友好的基本功能。
v1.2.0
2020-02-05 13:49 UTC
Requires
- php: ^5.6 || ^7.0
This package is auto-updated.
Last update: 2024-09-06 00:23:20 UTC
README
ArashDalir/ClassFriendship
提供了模拟 C++ 中类友好的基本功能。
安装
使用以下命令将仓库添加到您的项目中
composer require arashdalir/php-classfriendship
或者将以下行添加到您的 composer.json 文件中
{ "require": { "arashdalir/php-classfriendship": "dev-master" } }
用法
需要使用 trait Friends
在类实现中使用。可以这样定义一个新的友情:
<?php namespace Test; include "vendor/autoload.php"; use ArashDalir\ClassFriendship\Friends; use ArashDalir\ClassFriendship\FriendshipTypes; class A{ use Friends; protected $parameter; function __construct() { static::addFriendship(B::class, FriendshipTypes::CAN_READ|FriendshipTypes::CAN_WRITE); } } class B{ function testFriendship(){ $a = new A(); $a->parameter = "B can access this!"; print_r($a); } } class C{ function testFriendship() { $a = new A(); $a->parameter = "C cannot access this! this will throw NotFriendsException"; print_r($a); } } $b = new B(); $c = new C(); $b->testFriendship(); $c->testFriendship(); /* prints: Test\A Object ( [parameter:protected] => B can access this! ) throws: PHP Fatal error: Uncaught exception 'ArashDalir\ClassFriendship\Exceptions\NotFriendsException' with message 'Class "Test\C" is not a friend of class "Test\A".' in D:\gamp\htdocs\tools\github\ClassFriendship\src\Friends.php:90 Stack trace: #0 D:\gamp\htdocs\tools\github\ClassFriendship\src\Friends.php(62): Test\A->set('parameter', 'C cannot access...') #1 D:\gamp\htdocs\tools\github\ClassFriendship\demo.php(34): Test\A->__set('parameter', 'C cannot access...') #2 D:\gamp\htdocs\tools\github\ClassFriendship\demo.php(44): Test\C->testFriendship() #3 {main} thrown in D:\gamp\htdocs\tools\github\ClassFriendship\src\Friends.php on line 90 */