php一个类引用另一个类的方法的写法

default.php:

<?php
namespace SiteInfo{
   class Site{
        var $url;
        var $title;
        
        function setUrl($par){
            $this->url=$par;
        }
        
        function getUrl(){
            echo $this->url.PHP_EOL;
        }
        
        function setTitle($par){
            $this->title=$par;
        }
        
        function getTitle(){
            echo $this->title.PHP_EOL;
        }
    }
}
?>

index.php:

<?php
 namespace DoSomething{
     require ('default.php');//require只是引用一次,报错后就中终断执行,include是每次加载都执行,报错后只是提示,后续程序继续执行
     use SiteInfo\Site;//引用命名空间\类名
     class myClass{
         function getSite(){
             $taobao=new Site();//实例化方法,这些实例化只能写到类的方法里面不能再类里面实例化
             $taobao->setUrl('hello word~~!!!!!!!@!!!!@#$%YUI');
             $result = $taobao->getUrl();
             echo $result;
         }
     }
     $myClass = new myClass();
     $myClass->getSite();//类方法调用
 }

?>

猜你喜欢

转载自www.cnblogs.com/llcdbk/p/9914856.html