PHP控制台脚本/传递默认参数/重构fopen()fread()fwrite()fclose()
作者:互联网
我写了这个小脚本来为Ubuntu Gnome换成Numix主题的颜色:
<?php
$oldColor = $argv[1];
$newColor = $argv[2];
// defaults
// $oldColor = 'd64937';
// $newColor = 'f66153';
$path = '/usr/share/themes/Numix/gtk-3.0/gtk-dark.css';
$fileRead = fopen($path, 'r');
$contents = fread($fileRead, filesize($path));
$newContents = str_replace($oldColor, $newColor, $contents);
$fileWrite = fopen($path, 'w');
fwrite($fileWrite, $newContents);
fclose($fileWrite);
?>
只要我传递两个参数,脚本就可以正常工作.
>如何为参数设置默认值?
>是否应该重构使用file_put_contents()?
解决方法:
<?php
// How do I set defaults for the arguments?
$oldColor = !empty($argv[1]) ? $argv[1] : 'd64937';
$newColor = !empty($argv[2]) ? $argv[2] : 'f66153';
$file = '/usr/share/themes/Numix/gtk-3.0/gtk-dark.css';
// Your choice whether its cleaner, I think so.
file_put_contents(
$file,
str_replace(
$oldColor,
$newColor,
file_get_contents($file)
)
);
?>
标签:fread,fwrite,fopen,fclose,php 来源: https://codeday.me/bug/20191028/1955241.html