> php教程 > PHP开发 > 본문

PHP 객체지향 프로그래밍의 네임스페이스 및 자동으로 로드되는 클래스에 대한 자세한 설명

高洛峰
풀어 주다: 2016-12-30 10:07:16
원래의
1115명이 탐색했습니다.

이 기사의 예에서는 PHP 객체 지향 프로그래밍의 네임스페이스와 자동 로딩 클래스를 설명합니다. 참고용으로 모든 사람과 공유하세요. 클래스 이름의 중복과 오류를 피하기 위해 세부 사항은

네임스페이스

입니다.

<?php
require_once "useful/Outputter.php";
class Outputter {
  // output data
  private $name;
  public function setName($name) {
    $this->name = $name;
  }
  public function getName() {
    return $this->name;
  }
}
$obj = new Outputter(); // 同一命名空间下,类名不能相同,默认命名空间为空。空也是一种命名空间。
$obj -> setName("Jack");
print $obj->getName();
//namespace useful; // 更改命名空间,否则查询不到Hello类,Fatal error: Class &#39;my\Hello&#39; not found
$hello = new Hello();
?>
<?php
// useful/Outputter.php
namespace useful; // 命名空间
class Outputter {
  //
}
class Hello {
}
?>
로그인 후 복사

네임스페이스에서 클래스를 호출하는 방법

<?php
namespace com\getinstance\util;
class Debug {
  static function helloWorld() {
    print "hello from Debug\n";
  }
}
namespace main;
// com\getinstance\util\Debug::helloWorld(); // 找不到Debug类
\com\getinstance\util\Debug::helloWorld(); // 加斜杠之后,就从根部去寻找了。
// outPut:hello from Debug
?>
로그인 후 복사

키워드 사용

<?php
namespace com\getinstance\util;
class Debug {
  static function helloWorld() {
    print "hello from Debug\n";
  }
}
namespace main;
use com\getinstance\util;
//Debug::helloWorld(); //Fatal error: Class &#39;main\Debug&#39; not found
util\Debug::helloWorld();
?>
로그인 후 복사

클래스를 직접 호출하려면 다음 처리를 사용하세요

<?php
namespace com\getinstance\util;
class Debug {
  static function helloWorld() {
    print "hello from Debug\n";
  }
}
namespace main;
use com\getinstance\util\Debug; // 直接使用到类
Debug::helloWorld();
?>
로그인 후 복사

은 전역을 나타냅니다.

global.php

<?php
// no namespace
class Lister {
  public static function helloWorld() {
    print "hello from global\n";
  }
}
?>
<?php
namespace com\getinstance\util;
require_once &#39;global.php&#39;;
class Lister {
  public static function helloWorld() {
    print "hello from ".__NAMESPACE__."\n"; // __NAMESPACE__当前namespace
  }
}
Lister::helloWorld(); // access local
\Lister::helloWorld(); // access global
?>
로그인 후 복사

출력:

comgetinstanceutil에서 안녕하세요
hello from global

네임스페이스 + {}

<?php
namespace com\getinstance\util {
  class Debug {
    static function helloWorld() {
      print "hello from Debug\n";
    }
  }
}
namespace main {
  \com\getinstance\util\Debug::helloWorld();
}
?>
로그인 후 복사

출력:

hello from Debug

글로벌 네임스페이스

<?php
namespace { // 全局空间
  class Lister {
    public static function helloWorld() {
      print "hello from global\n";
    }
  }
}
namespace com\getinstance\util {
  class Lister {
    public static function helloWorld() {
      print "hello from ".__NAMESPACE__."\n";
    }
  }
  Lister::helloWorld(); // access local
  \Lister::helloWorld(); // access global
}
?>
로그인 후 복사

__autoload 자동 로딩 클래스

ShopProduct.php

<?php
class ShopProduct {
  function __construct() {
    print "ShopProduct constructor\n";
  }
}
?>
<?php
function __autoload( $classname ) { // 自动加载,根据类名加载类
  include_once( "$classname.php" );
}
$product = new ShopProduct( &#39;The Darkening&#39;, &#39;Harry&#39;, &#39;Hunter&#39;, 12.99 );
?>
로그인 후 복사

출력:

ShopProduct 생성자

추가 최적화 처리

는 폴더 business/ShopProduct.php

<?php
class business_ShopProduct { // 这里的类命名就要遵循规则了
  function __construct() {
    print "business_ShopProduct constructor\n";
  }
}
?>
<?php
function __autoload( $classname ) {
  $path = str_replace(&#39;_&#39;, DIRECTORY_SEPARATOR, $classname ); // 智能化处理
  require_once( "$path.php" );
}
$x = new ShopProduct();
$y = new business_ShopProduct();
?>
로그인 후 복사

출력:

ShopProduct 생성자

business_ShopProduct 생성자

이 기사가 PHP 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

PHP 객체지향 프로그래밍의 네임스페이스 및 자동 로딩 클래스에 대한 자세한 설명은 PHP 중국어 홈페이지를 참고해주세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!